当前位置:网站首页>C# Rectangle basic usage and picture cutting
C# Rectangle basic usage and picture cutting
2022-07-31 23:21:00 【Xiong Siyu】
目录
Rectangle(Int32, Int32, Int32, Int32)
1.判断Whether the two rectangles intersect
2.Find the rectangle where the two rectangles intersect and overlap
一、需求
Rectangles are very common in development,Such as the screenshot function,GDI+ 画图,Rectangle 的构造函数中,Four parameters are required,坐标x,y,宽度,高度,It also encapsulates other write methods,such as whether to intersect,The rectangle that overlaps where the two rectangles meet,According to the upper left,and the lower right coordinates to generate a rectangle and so on,Here's some introduction to constructors.
构造函数:
Rectangle(Point, Size)
Initialize with the specified position and size Rectangle 类的新实例.
public Rectangle (System.Drawing.Point location, System.Drawing.Size size);
参数:location Point Point,It represents the upper left corner of the rectangular area.size Size Size,It represents the width and height of the rectangular area.
Rectangle(Int32, Int32, Int32, Int32)
Initialize with the specified position and size Rectangle 类的新实例.
public Rectangle (int x, int y, int width, int height);
参数:x Int32 矩形左上角的 x 坐标.y Int32 矩形左上角的 y 坐标.width Int32 矩形的宽度.height Int32 矩形的高度.
二、常用的功能
1.判断Whether the two rectangles intersect
Check whether two rectangles intersect,返回值是布尔类型
Rectangle rectangle1 = new Rectangle(100,100,50,50);
Rectangle rectangle2 = new Rectangle(110,110,50,50);
bool isIntersect = rectangle1.IntersectsWith(rectangle2);
2.Find the rectangle where the two rectangles intersect and overlap
After the two rectangles intersect,According to the overlap of the two rectangles,Get a new rectangle
Rectangle rectangle1 = new Rectangle(100,100,50,50);
Rectangle rectangle2 = new Rectangle(110,110,50,50);
Rectangle overlap = Rectangle.Intersect(rectangle1, rectangle2);
3.案例
上面这两个API,A case is shown below
效果
上图可以看到,when the two images overlap,The overlapping part of the image is immediately displayed in the small picture next to it,另外,I output the judgment of coincidence in the console
界面设计
代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 矩形
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//图片列表
private string Img1Path = Application.StartupPath + "\\test.jpg";
//Stores a list of rectangles
List<Rectangle> PictureCuttingList = new List<Rectangle>();
//边长
int SideLength = 180;
private void Form1_Load(object sender, EventArgs e)
{
}
private void Button_Examine_Click(object sender, EventArgs e)
{
if (!System.IO.File.Exists(Img1Path))
{
Console.WriteLine("图片路径不存在:" + Img1Path);
return;
}
Bitmap bitmaps = new Bitmap(Img1Path);
Random random = new Random();
PictureCuttingList.Clear();
PictureBox_Coincide.Image = null;
for (int i = 0; i < 2; i++)
{
int x = random.Next(10, bitmaps.Width - SideLength);
int y = random.Next(10, bitmaps.Height - SideLength);
PictureCuttingList.Add(new Rectangle(new Point(x, y), new Size(SideLength, SideLength)));
}
//给图片画矩形
PictureBox_Template.Image = PaintingRectangle(PictureCuttingList, bitmaps);
//判断Whether the two rectangles intersect
Rectangle rectangle1 = PictureCuttingList[0];
Rectangle rectangle2 = PictureCuttingList[1];
bool isRect = rectangle1.IntersectsWith(rectangle2);
Console.WriteLine("Whether the two rectangles intersect:" + isRect);
if (isRect)
{
//The image of the part where the two rectangles intersect is displayed in the thumbnail
Rectangle overlap = Rectangle.Intersect(rectangle1, rectangle2);
Bitmap newBitmap = new Bitmap(Img1Path);
Bitmap cuttingBitmap = newBitmap.Clone(overlap, System.Drawing.Imaging.PixelFormat.DontCare);
PictureBox_Coincide.Image = cuttingBitmap;
}
}
/// <summary>
/// 给图片画矩形
/// </summary>
/// <param name="rectanglesList"></param>
/// <param name="bitmap"></param>
public Bitmap PaintingRectangle(List<Rectangle> rectanglesList, Bitmap bitmap)
{
Bitmap bit = null;
for (int i = 0; i < rectanglesList.Count; i++)
{
if (bit == null)
{
bit = DrawRectangleInPicture(bitmap, rectanglesList[i], Color.Red, 4, "索引:" + i, 25);
}
else
{
Bitmap newBit = new Bitmap(bit);
bit.Dispose();
bit = DrawRectangleInPicture(newBit, rectanglesList[i], Color.Red, 4, "索引:" + i, 25);
}
}
if (bit == null)
{
Console.WriteLine("bit等于null");
return null;
}
return bit;
}
/// <summary>
/// 图片上画矩形和标记文字
/// </summary>
/// <param name="bmp">图片bitmap</param>
/// <param name="imgRectangle">矩形</param>
/// <param name="lineColor">线条的颜色</param>
/// <param name="lineWidth">线条</param>
/// <param name="text">矩形的文本</param>
/// <param name="fontSize">字体大小</param>
/// <param name="ds">线条的线型</param>
/// <returns></returns>
public Bitmap DrawRectangleInPicture(Bitmap bmp, Rectangle imgRectangle, Color lineColor, int lineWidth, string text, int fontSize, DashStyle ds = DashStyle.Solid)
{
if (bmp == null) return null;
if (imgRectangle == null) return null;
if (lineColor == null) return null;
if (lineWidth == 0) return null;
if (fontSize == 0) return null;
if (string.IsNullOrEmpty(text)) return null;
Point pos = imgRectangle.Location;
Size size = imgRectangle.Size;
Graphics g = Graphics.FromImage(bmp);
Brush brush = new SolidBrush(lineColor);
Pen pen = new Pen(brush, lineWidth);
pen.DashStyle = ds;
//The origin of the drawing coordinates(用于测试)
g.DrawEllipse(pen, new Rectangle(pos.X, pos.Y, 15, 15));
//画矩形
//int rectX = pos.X - (size.Width / 2);
//int rectY = pos.Y - (size.Height / 2);
//g.DrawRectangle(pen, rectX, rectY, size.Width, size.Height);
g.DrawRectangle(pen, pos.X, pos.Y, size.Width, size.Height);
Font myFont = new Font("宋体", fontSize, FontStyle.Regular);
Brush bush = new SolidBrush(lineColor);//填充的颜色
//Calculation of font position
SizeF sizeF = g.MeasureString(text, myFont);
//int fontPosX = (int)(pos.X - (sizeF.Width / 2));
//int fontPosY = (int)(pos.Y + (sizeF.Height / 2) + (size.Height / 2));
//g.DrawString(text, myFont, bush, fontPosX, fontPosY);
int fontPosX = (int)(pos.X + (size.Width / 2) - (sizeF.Width / 2));
int fontPosY = (int)(pos.Y + (size.Height / 2) - (sizeF.Height / 2));
g.DrawString(text, myFont, bush, fontPosX, fontPosY);
g.Dispose();
return bmp;
}
}
}
三、切图Demo
切图的demoSimilar to the above case
界面
效果
上面gifThe last picture of the picture
代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Crop Thumbnail
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string Img1Path = Application.StartupPath + "\\test.jpg";
List<PictureBox> PictureBoxesList = new List<PictureBox>();
List<Rectangle> PictureCuttingList = new List<Rectangle>();
//The width of the cut thumbnail
int ImgWidth = 180;
private void Form1_Load(object sender, EventArgs e)
{
TextBox_ImaPath.Text = Img1Path;
PictureBoxesList.Add(pictureBox1);
PictureBoxesList.Add(pictureBox2);
PictureBoxesList.Add(pictureBox3);
PictureBoxesList.Add(pictureBox4);
PictureBoxesList.Add(pictureBox5);
}
/// <summary>
/// 选择图片路径
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_SelectImg_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = true;//该值确定是否可以选择多个文件
dialog.Title = "请选择文件";
dialog.Filter = "所有文件(*.*)|*.*";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
TextBox_ImaPath.Text = dialog.FileName;
Img1Path = dialog.FileName;
PictureBox_Template.Image = new Bitmap(Img1Path);
}
}
/// <summary>
/// Generate a rectangle plot
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Examine_Click(object sender, EventArgs e)
{
if (!System.IO.File.Exists(Img1Path))
{
Console.WriteLine("图片路径不存在:" + Img1Path);
return;
}
Bitmap bitmaps = new Bitmap(Img1Path);
Random random = new Random();
//Console.WriteLine(string.Format("总宽度:{0} 总高度:{1}", Bitmaps.Width, Bitmaps.Height));
PictureCuttingList.Clear();
for (int i = 0; i < 2; i++)
{
int x = random.Next(10, bitmaps.Width - ImgWidth);
int y = random.Next(10, bitmaps.Height - ImgWidth);
//In this way, writing the rectangle will exceed the scope of the picture,可以用来测试
//int x = random.Next(10, Bitmaps.Width);
//int y = random.Next(10, Bitmaps.Height);
//Console.WriteLine(string.Format("索引值: {0} x: {1}, y: {2}", i, x, y));
PictureCuttingList.Add(new Rectangle(new Point(x, y), new Size(ImgWidth, ImgWidth)));
}
//给图片画矩形
PictureBox_Template.Image = PaintingRectangle(PictureCuttingList, bitmaps);
}
/// <summary>
/// 开始切割
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Cutting_Click(object sender, EventArgs e)
{
if (!System.IO.File.Exists(Img1Path))
{
Console.WriteLine("图片路径不存在:" + Img1Path);
return;
}
if (PictureCuttingList.Count == 0)
{
Console.WriteLine("PictureCuttingList不能为空");
return;
}
Bitmap bitmaps = new Bitmap(Img1Path);
List<Bitmap> cuttingList = CuttingHandle(PictureCuttingList, bitmaps);
if (cuttingList != null && cuttingList.Count > 0)
{
for (int i = 0; i < cuttingList.Count; i++)
{
PictureBoxesList[i].Image = cuttingList[i];
}
}
}
/// <summary>
/// 给图片画矩形
/// </summary>
/// <param name="rectanglesList"></param>
/// <param name="bitmap"></param>
public Bitmap PaintingRectangle(List<Rectangle> rectanglesList, Bitmap bitmap)
{
Bitmap bit = null;
for (int i = 0; i < rectanglesList.Count; i++)
{
if (bit == null)
{
bit = DrawRectangleInPicture(bitmap, rectanglesList[i], Color.Red, 4, "索引:" + i, 25);
}
else
{
Bitmap newBit = new Bitmap(bit);
bit.Dispose();
bit = DrawRectangleInPicture(newBit, rectanglesList[i], Color.Red, 4, "索引:" + i, 25);
}
}
if (bit == null)
{
Console.WriteLine("bit等于null");
return null;
}
return bit;
}
/// <summary>
/// 裁切图片(The coordinates of the slice have the upper left corner as the origin)
/// </summary>
/// <param name="pictureCuttingList">Area data list</param>
/// <param name="bitmap">图片bitmap</param>
/// <returns>List of images for slices</returns>
public List<Bitmap> CuttingHandle(List<Rectangle> pictureCuttingList, Bitmap bitmap)
{
if (pictureCuttingList == null || pictureCuttingList.Count == 0)
{
Console.WriteLine("[CuttingHandle]pictureCuttingList不能为空");
return null;
}
if (bitmap == null)
{
Console.WriteLine("[CuttingHandle]图片bitmap不能为空");
return null;
}
List<Bitmap> bitmapList = new List<Bitmap>();
for (int i = 0; i < pictureCuttingList.Count; i++)
{
Rectangle rectangle = pictureCuttingList[i];
if(rectangle == null)
{
Console.WriteLine("[CuttingHandle]pictureCuttingListA value is empty,index:" + i);
return null;
}
//Determine whether the coordinates are within the image range
Point pos = rectangle.Location;
Size size = rectangle.Size;
if(pos.X < 0 || pos.X + size.Width > bitmap.Width)
{
Console.WriteLine("[CuttingHandle]当前区域XAxes are out of picture,索引是:" + i);
return null;
}
if(pos.Y < 0 || pos.Y + size.Height > bitmap.Height)
{
Console.WriteLine("[CuttingHandle]当前区域YAxes are out of picture,索引是:" + i);
return null;
}
Bitmap cuttingBitmap = bitmap.Clone(rectangle, System.Drawing.Imaging.PixelFormat.DontCare);
bitmapList.Add(cuttingBitmap);
}
if (bitmapList.Count > 0)
return bitmapList;
return null;
}
/// <summary>
/// 图片上画矩形和标记文字
/// </summary>
/// <param name="bmp">图片bitmap</param>
/// <param name="imgRectangle">矩形</param>
/// <param name="lineColor">线条的颜色</param>
/// <param name="lineWidth">线条</param>
/// <param name="text">矩形的文本</param>
/// <param name="fontSize">字体大小</param>
/// <param name="ds">线条的线型</param>
/// <returns></returns>
public Bitmap DrawRectangleInPicture(Bitmap bmp, Rectangle imgRectangle, Color lineColor, int lineWidth, string text, int fontSize, DashStyle ds = DashStyle.Solid)
{
if (bmp == null) return null;
if (imgRectangle == null) return null;
if (lineColor == null) return null;
if (lineWidth == 0) return null;
if (fontSize == 0) return null;
if (string.IsNullOrEmpty(text)) return null;
Point pos = imgRectangle.Location;
Size size = imgRectangle.Size;
Graphics g = Graphics.FromImage(bmp);
Brush brush = new SolidBrush(lineColor);
Pen pen = new Pen(brush, lineWidth);
pen.DashStyle = ds;
//The origin of the drawing coordinates(用于测试)
g.DrawEllipse(pen, new Rectangle(pos.X, pos.Y, 15, 15));
//画矩形
//int rectX = pos.X - (size.Width / 2);
//int rectY = pos.Y - (size.Height / 2);
//g.DrawRectangle(pen, rectX, rectY, size.Width, size.Height);
g.DrawRectangle(pen, pos.X, pos.Y, size.Width, size.Height);
Font myFont = new Font("宋体", fontSize, FontStyle.Regular);
Brush bush = new SolidBrush(lineColor);//填充的颜色
//Calculation of font position
SizeF sizeF = g.MeasureString(text, myFont);
//int fontPosX = (int)(pos.X - (sizeF.Width / 2));
//int fontPosY = (int)(pos.Y + (sizeF.Height / 2) + (size.Height / 2));
//g.DrawString(text, myFont, bush, fontPosX, fontPosY);
int fontPosX = (int)(pos.X + (size.Width / 2) - (sizeF.Width / 2));
int fontPosY = (int)(pos.Y + (size.Height / 2) - (sizeF.Height / 2));
g.DrawString(text, myFont, bush, fontPosX, fontPosY);
g.Dispose();
return bmp;
}
}
}
源码地址:点击下载
结束
如果这个帖子对你有用,欢迎 关注 + 点赞 + 留言,谢谢
end
边栏推荐
- 无状态与有状态的区别
- The difference between adding or not adding the ref keyword when a variable of reference type is used as a parameter in a method call in C#
- Pytest初体验
- C#中引用类型的变量做为参数在方法调用时加不加 ref 关键字的不同之处
- The uniapp applet checks and prompts for updates
- How to import a Golang external package and use it?
- #yyds dry goods inventory# Interview must brush TOP101: the entry node of the ring in the linked list
- useragent online lookup
- 数据分析(一)——matplotlib
- 如何撰写出一篇优质的数码类好物推荐文
猜你喜欢
支付模块实现
2022-07-31:给出一个有n个点,m条有向边的图, 你可以施展魔法,把有向边,变成无向边, 比如A到B的有向边,权重为7。施展魔法之后,A和B通过该边到达彼此的代价都是7。 求,允许施展一次魔法
How to identify fake reptiles?
[NLP] What is the memory of the model!
useragent online lookup
【1161. 最大层内元素和】
GateWay implements load balancing
Unity-通过预制件和克隆方法动态实现各个UGUI下控件的创建和显示
Write a database document management tool based on WPF repeating the wheel (1)
/etc/sysconfig/network-scripts 配置网卡
随机推荐
Flutter教程之 02 Flutter 桌面程序开发入门教程运行hello world (教程含源码)
2022年CSP-J1 CSP-S1 第1轮初赛 报名指南
10大主流3D建模技术
Several methods for deleting specified elements in Golang slices
网络安全--通过握手包破解WiFi(详细教程)
Shell常用脚本:Nexus批量上传本地仓库增强版脚本(强烈推荐)
Dry goods | 10 tips for MySQL add, delete, change query performance optimization
Judging decimal points and rounding of decimal operations in Golang
标段参数说明
SQL27 View user details of different age groups
Quick Start Tutorial for flyway
UOS统信系统 - WindTerm使用
什么是客户画像管理?
MLP神经网络,GRNN神经网络,SVM神经网络以及深度学习神经网络对比识别人体健康非健康数据
GateWay implements load balancing
@JsonFormat(pattern="yyyy-MM-dd") time difference problem
SQL注入 Less47(报错注入) 和Less49(时间盲注)
SQL注入 Less42(POST型堆叠注入)
Binary tree non-recursive traversal
C#中引用类型的变量做为参数在方法调用时加不加 ref 关键字的不同之处