• C# Rectangle基本用法和图片切割


    目录

    一、需求

    Rectangle(Point, Size)

    Rectangle(Int32, Int32, Int32, Int32)

    二、常用的功能

    1.判断两个矩形是否相交

    2.求出两矩形相交重叠处的矩形

    3.案例

    三、切图Demo

    结束


    一、需求

    矩形在开发中非常常见,比如截图功能,GDI+ 画图,Rectangle 的构造函数中,需要提供四个参数,坐标x,y,宽度,高度,另外还封装了其他的一写方法,比如是否相交,两矩形相交处重叠的矩形,根据左上,和右下坐标生成矩形等等方法,下面是构造函数的一些介绍。

    构造函数:

    Rectangle(Point, Size)

    用指定的位置和大小初始化 Rectangle 类的新实例。

    public Rectangle (System.Drawing.Point location, System.Drawing.Size size);

    参数:location Point  Point,它表示矩形区域的左上角。size Size  Size,它表示矩形区域的宽度和高度。

    Rectangle(Int32, Int32, Int32, Int32)

    用指定的位置和大小初始化 Rectangle 类的新实例。

    public Rectangle (int x, int y, int width, int height);

    参数:x Int32 矩形左上角的 x 坐标。y Int32 矩形左上角的 y 坐标。width Int32 矩形的宽度。height Int32 矩形的高度。


     

    二、常用的功能

    1.判断两个矩形是否相交

    判断连个矩形是否相交,返回值是布尔类型

    1. Rectangle rectangle1 = new Rectangle(100,100,50,50);
    2. Rectangle rectangle2 = new Rectangle(110,110,50,50);
    3. bool isIntersect = rectangle1.IntersectsWith(rectangle2);

    2.求出两矩形相交重叠处的矩形

    两个矩形相交后,根据两个矩形的重叠处,得出一个新的矩形

    1. Rectangle rectangle1 = new Rectangle(100,100,50,50);
    2. Rectangle rectangle2 = new Rectangle(110,110,50,50);
    3. Rectangle overlap = Rectangle.Intersect(rectangle1, rectangle2);

    3.案例

    上面这两个API,下面就用一个案例来展示

    效果

    上图可以看到,当两个图像重合后,就立马将重合的部分图像显示在旁边的小图中了,另外,我将是否重合的判断输出在控制台中了

    界面设计

    代码

    1. using System;
    2. using System.Collections.Generic;
    3. using System.ComponentModel;
    4. using System.Data;
    5. using System.Drawing;
    6. using System.Drawing.Drawing2D;
    7. using System.Linq;
    8. using System.Text;
    9. using System.Threading.Tasks;
    10. using System.Windows.Forms;
    11. namespace 矩形
    12. {
    13. public partial class Form1 : Form
    14. {
    15. public Form1()
    16. {
    17. InitializeComponent();
    18. }
    19. //图片列表
    20. private string Img1Path = Application.StartupPath + "\\test.jpg";
    21. //存储矩形列表
    22. List PictureCuttingList = new List();
    23. //边长
    24. int SideLength = 180;
    25. private void Form1_Load(object sender, EventArgs e)
    26. {
    27. }
    28. private void Button_Examine_Click(object sender, EventArgs e)
    29. {
    30. if (!System.IO.File.Exists(Img1Path))
    31. {
    32. Console.WriteLine("图片路径不存在:" + Img1Path);
    33. return;
    34. }
    35. Bitmap bitmaps = new Bitmap(Img1Path);
    36. Random random = new Random();
    37. PictureCuttingList.Clear();
    38. PictureBox_Coincide.Image = null;
    39. for (int i = 0; i < 2; i++)
    40. {
    41. int x = random.Next(10, bitmaps.Width - SideLength);
    42. int y = random.Next(10, bitmaps.Height - SideLength);
    43. PictureCuttingList.Add(new Rectangle(new Point(x, y), new Size(SideLength, SideLength)));
    44. }
    45. //给图片画矩形
    46. PictureBox_Template.Image = PaintingRectangle(PictureCuttingList, bitmaps);
    47. //判断两个矩形是否相交
    48. Rectangle rectangle1 = PictureCuttingList[0];
    49. Rectangle rectangle2 = PictureCuttingList[1];
    50. bool isRect = rectangle1.IntersectsWith(rectangle2);
    51. Console.WriteLine("两个矩形是否相交:" + isRect);
    52. if (isRect)
    53. {
    54. //两个矩形相交部分图片显示到小图中
    55. Rectangle overlap = Rectangle.Intersect(rectangle1, rectangle2);
    56. Bitmap newBitmap = new Bitmap(Img1Path);
    57. Bitmap cuttingBitmap = newBitmap.Clone(overlap, System.Drawing.Imaging.PixelFormat.DontCare);
    58. PictureBox_Coincide.Image = cuttingBitmap;
    59. }
    60. }
    61. ///
    62. /// 给图片画矩形
    63. ///
    64. ///
    65. ///
    66. public Bitmap PaintingRectangle(List rectanglesList, Bitmap bitmap)
    67. {
    68. Bitmap bit = null;
    69. for (int i = 0; i < rectanglesList.Count; i++)
    70. {
    71. if (bit == null)
    72. {
    73. bit = DrawRectangleInPicture(bitmap, rectanglesList[i], Color.Red, 4, "索引:" + i, 25);
    74. }
    75. else
    76. {
    77. Bitmap newBit = new Bitmap(bit);
    78. bit.Dispose();
    79. bit = DrawRectangleInPicture(newBit, rectanglesList[i], Color.Red, 4, "索引:" + i, 25);
    80. }
    81. }
    82. if (bit == null)
    83. {
    84. Console.WriteLine("bit等于null");
    85. return null;
    86. }
    87. return bit;
    88. }
    89. ///
    90. /// 图片上画矩形和标记文字
    91. ///
    92. /// 图片bitmap
    93. /// 矩形
    94. /// 线条的颜色
    95. /// 线条
    96. /// 矩形的文本
    97. /// 字体大小
    98. /// 线条的线型
    99. ///
    100. public Bitmap DrawRectangleInPicture(Bitmap bmp, Rectangle imgRectangle, Color lineColor, int lineWidth, string text, int fontSize, DashStyle ds = DashStyle.Solid)
    101. {
    102. if (bmp == null) return null;
    103. if (imgRectangle == null) return null;
    104. if (lineColor == null) return null;
    105. if (lineWidth == 0) return null;
    106. if (fontSize == 0) return null;
    107. if (string.IsNullOrEmpty(text)) return null;
    108. Point pos = imgRectangle.Location;
    109. Size size = imgRectangle.Size;
    110. Graphics g = Graphics.FromImage(bmp);
    111. Brush brush = new SolidBrush(lineColor);
    112. Pen pen = new Pen(brush, lineWidth);
    113. pen.DashStyle = ds;
    114. //画坐标的原点(用于测试)
    115. g.DrawEllipse(pen, new Rectangle(pos.X, pos.Y, 15, 15));
    116. //画矩形
    117. //int rectX = pos.X - (size.Width / 2);
    118. //int rectY = pos.Y - (size.Height / 2);
    119. //g.DrawRectangle(pen, rectX, rectY, size.Width, size.Height);
    120. g.DrawRectangle(pen, pos.X, pos.Y, size.Width, size.Height);
    121. Font myFont = new Font("宋体", fontSize, FontStyle.Regular);
    122. Brush bush = new SolidBrush(lineColor);//填充的颜色
    123. //字体位置的计算
    124. SizeF sizeF = g.MeasureString(text, myFont);
    125. //int fontPosX = (int)(pos.X - (sizeF.Width / 2));
    126. //int fontPosY = (int)(pos.Y + (sizeF.Height / 2) + (size.Height / 2));
    127. //g.DrawString(text, myFont, bush, fontPosX, fontPosY);
    128. int fontPosX = (int)(pos.X + (size.Width / 2) - (sizeF.Width / 2));
    129. int fontPosY = (int)(pos.Y + (size.Height / 2) - (sizeF.Height / 2));
    130. g.DrawString(text, myFont, bush, fontPosX, fontPosY);
    131. g.Dispose();
    132. return bmp;
    133. }
    134. }
    135. }

    三、切图Demo

    切图的demo和上面的案例的功能类似

    界面

    效果

     上面gif图片的最后画面

     代码

    1. using System;
    2. using System.Collections.Generic;
    3. using System.ComponentModel;
    4. using System.Data;
    5. using System.Drawing;
    6. using System.Drawing.Drawing2D;
    7. using System.Linq;
    8. using System.Text;
    9. using System.Threading;
    10. using System.Threading.Tasks;
    11. using System.Windows.Forms;
    12. namespace 裁切小图
    13. {
    14. public partial class Form1 : Form
    15. {
    16. public Form1()
    17. {
    18. InitializeComponent();
    19. }
    20. string Img1Path = Application.StartupPath + "\\test.jpg";
    21. List PictureBoxesList = new List();
    22. List PictureCuttingList = new List();
    23. //切割小图的宽度
    24. int ImgWidth = 180;
    25. private void Form1_Load(object sender, EventArgs e)
    26. {
    27. TextBox_ImaPath.Text = Img1Path;
    28. PictureBoxesList.Add(pictureBox1);
    29. PictureBoxesList.Add(pictureBox2);
    30. PictureBoxesList.Add(pictureBox3);
    31. PictureBoxesList.Add(pictureBox4);
    32. PictureBoxesList.Add(pictureBox5);
    33. }
    34. ///
    35. /// 选择图片路径
    36. ///
    37. ///
    38. ///
    39. private void Button_SelectImg_Click(object sender, EventArgs e)
    40. {
    41. OpenFileDialog dialog = new OpenFileDialog();
    42. dialog.Multiselect = true;//该值确定是否可以选择多个文件
    43. dialog.Title = "请选择文件";
    44. dialog.Filter = "所有文件(*.*)|*.*";
    45. if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    46. {
    47. TextBox_ImaPath.Text = dialog.FileName;
    48. Img1Path = dialog.FileName;
    49. PictureBox_Template.Image = new Bitmap(Img1Path);
    50. }
    51. }
    52. ///
    53. /// 生成矩形图
    54. ///
    55. ///
    56. ///
    57. private void Button_Examine_Click(object sender, EventArgs e)
    58. {
    59. if (!System.IO.File.Exists(Img1Path))
    60. {
    61. Console.WriteLine("图片路径不存在:" + Img1Path);
    62. return;
    63. }
    64. Bitmap bitmaps = new Bitmap(Img1Path);
    65. Random random = new Random();
    66. //Console.WriteLine(string.Format("总宽度:{0} 总高度:{1}", Bitmaps.Width, Bitmaps.Height));
    67. PictureCuttingList.Clear();
    68. for (int i = 0; i < 2; i++)
    69. {
    70. int x = random.Next(10, bitmaps.Width - ImgWidth);
    71. int y = random.Next(10, bitmaps.Height - ImgWidth);
    72. //这样写矩形会超出图片范围,可以用来测试
    73. //int x = random.Next(10, Bitmaps.Width);
    74. //int y = random.Next(10, Bitmaps.Height);
    75. //Console.WriteLine(string.Format("索引值: {0} x: {1}, y: {2}", i, x, y));
    76. PictureCuttingList.Add(new Rectangle(new Point(x, y), new Size(ImgWidth, ImgWidth)));
    77. }
    78. //给图片画矩形
    79. PictureBox_Template.Image = PaintingRectangle(PictureCuttingList, bitmaps);
    80. }
    81. ///
    82. /// 开始切割
    83. ///
    84. ///
    85. ///
    86. private void Button_Cutting_Click(object sender, EventArgs e)
    87. {
    88. if (!System.IO.File.Exists(Img1Path))
    89. {
    90. Console.WriteLine("图片路径不存在:" + Img1Path);
    91. return;
    92. }
    93. if (PictureCuttingList.Count == 0)
    94. {
    95. Console.WriteLine("PictureCuttingList不能为空");
    96. return;
    97. }
    98. Bitmap bitmaps = new Bitmap(Img1Path);
    99. List cuttingList = CuttingHandle(PictureCuttingList, bitmaps);
    100. if (cuttingList != null && cuttingList.Count > 0)
    101. {
    102. for (int i = 0; i < cuttingList.Count; i++)
    103. {
    104. PictureBoxesList[i].Image = cuttingList[i];
    105. }
    106. }
    107. }
    108. ///
    109. /// 给图片画矩形
    110. ///
    111. ///
    112. ///
    113. public Bitmap PaintingRectangle(List rectanglesList, Bitmap bitmap)
    114. {
    115. Bitmap bit = null;
    116. for (int i = 0; i < rectanglesList.Count; i++)
    117. {
    118. if (bit == null)
    119. {
    120. bit = DrawRectangleInPicture(bitmap, rectanglesList[i], Color.Red, 4, "索引:" + i, 25);
    121. }
    122. else
    123. {
    124. Bitmap newBit = new Bitmap(bit);
    125. bit.Dispose();
    126. bit = DrawRectangleInPicture(newBit, rectanglesList[i], Color.Red, 4, "索引:" + i, 25);
    127. }
    128. }
    129. if (bit == null)
    130. {
    131. Console.WriteLine("bit等于null");
    132. return null;
    133. }
    134. return bit;
    135. }
    136. ///
    137. /// 裁切图片(切片的坐标以左上角为原点)
    138. ///
    139. /// 区域数据列表
    140. /// 图片bitmap
    141. /// 切片的图片列表
    142. public List CuttingHandle(List pictureCuttingList, Bitmap bitmap)
    143. {
    144. if (pictureCuttingList == null || pictureCuttingList.Count == 0)
    145. {
    146. Console.WriteLine("[CuttingHandle]pictureCuttingList不能为空");
    147. return null;
    148. }
    149. if (bitmap == null)
    150. {
    151. Console.WriteLine("[CuttingHandle]图片bitmap不能为空");
    152. return null;
    153. }
    154. List bitmapList = new List();
    155. for (int i = 0; i < pictureCuttingList.Count; i++)
    156. {
    157. Rectangle rectangle = pictureCuttingList[i];
    158. if(rectangle == null)
    159. {
    160. Console.WriteLine("[CuttingHandle]pictureCuttingList有值为空,index:" + i);
    161. return null;
    162. }
    163. //判断坐标是否在图片范围内
    164. Point pos = rectangle.Location;
    165. Size size = rectangle.Size;
    166. if(pos.X < 0 || pos.X + size.Width > bitmap.Width)
    167. {
    168. Console.WriteLine("[CuttingHandle]当前区域X轴超出图片范围,索引是:" + i);
    169. return null;
    170. }
    171. if(pos.Y < 0 || pos.Y + size.Height > bitmap.Height)
    172. {
    173. Console.WriteLine("[CuttingHandle]当前区域Y轴超出图片范围,索引是:" + i);
    174. return null;
    175. }
    176. Bitmap cuttingBitmap = bitmap.Clone(rectangle, System.Drawing.Imaging.PixelFormat.DontCare);
    177. bitmapList.Add(cuttingBitmap);
    178. }
    179. if (bitmapList.Count > 0)
    180. return bitmapList;
    181. return null;
    182. }
    183. ///
    184. /// 图片上画矩形和标记文字
    185. ///
    186. /// 图片bitmap
    187. /// 矩形
    188. /// 线条的颜色
    189. /// 线条
    190. /// 矩形的文本
    191. /// 字体大小
    192. /// 线条的线型
    193. ///
    194. public Bitmap DrawRectangleInPicture(Bitmap bmp, Rectangle imgRectangle, Color lineColor, int lineWidth, string text, int fontSize, DashStyle ds = DashStyle.Solid)
    195. {
    196. if (bmp == null) return null;
    197. if (imgRectangle == null) return null;
    198. if (lineColor == null) return null;
    199. if (lineWidth == 0) return null;
    200. if (fontSize == 0) return null;
    201. if (string.IsNullOrEmpty(text)) return null;
    202. Point pos = imgRectangle.Location;
    203. Size size = imgRectangle.Size;
    204. Graphics g = Graphics.FromImage(bmp);
    205. Brush brush = new SolidBrush(lineColor);
    206. Pen pen = new Pen(brush, lineWidth);
    207. pen.DashStyle = ds;
    208. //画坐标的原点(用于测试)
    209. g.DrawEllipse(pen, new Rectangle(pos.X, pos.Y, 15, 15));
    210. //画矩形
    211. //int rectX = pos.X - (size.Width / 2);
    212. //int rectY = pos.Y - (size.Height / 2);
    213. //g.DrawRectangle(pen, rectX, rectY, size.Width, size.Height);
    214. g.DrawRectangle(pen, pos.X, pos.Y, size.Width, size.Height);
    215. Font myFont = new Font("宋体", fontSize, FontStyle.Regular);
    216. Brush bush = new SolidBrush(lineColor);//填充的颜色
    217. //字体位置的计算
    218. SizeF sizeF = g.MeasureString(text, myFont);
    219. //int fontPosX = (int)(pos.X - (sizeF.Width / 2));
    220. //int fontPosY = (int)(pos.Y + (sizeF.Height / 2) + (size.Height / 2));
    221. //g.DrawString(text, myFont, bush, fontPosX, fontPosY);
    222. int fontPosX = (int)(pos.X + (size.Width / 2) - (sizeF.Width / 2));
    223. int fontPosY = (int)(pos.Y + (size.Height / 2) - (sizeF.Height / 2));
    224. g.DrawString(text, myFont, bush, fontPosX, fontPosY);
    225. g.Dispose();
    226. return bmp;
    227. }
    228. }
    229. }

     源码地址:点击下载

    结束

    如果这个帖子对你有用,欢迎 关注 + 点赞 + 留言,谢谢

    end

  • 相关阅读:
    Mybatis-plus怎么忽略映射字段
    如何使用 arrayList.removeAll(Collection<?> c)?
    前端vue学习笔记——路由
    EMC简述01
    【错误记录】Python 中使用 PySpark 数据计算报错 ( SparkException: Python worker failed to connect back. )
    【pytorch问题解决】OSError: [WinError 1455] 页面文件太小,无法完成操作。
    MySQL主从复制
    美容院管理系统有哪些促销方式?
    机器人过程自动化(RPA)入门 7. 处理用户事件和助手机器人
    vue3 实现pdf预览
  • 原文地址:https://blog.csdn.net/qq_38693757/article/details/126074911