C# winform开发:Graphics、pictureBox同时画多个矩形
C#的System.Drawing 命名空间提供了对 GDI+ 基本图形功能的访问
重点在于获取Graphics对象,例如:
Graphics g = panel1.CreateGraphics
事实上CreateGraphics继承自Control, 即基本每一种控件都有这个方法
Control.CreateGraphics
在pannel、form上画图都一样,这里以pictureBox为例。DrawRectangle函数为例画矩形,其他形状不在这里考虑,自己尝试很简单
画圆是画椭圆,只需g.DrawEllipse后两个int参数width,height要设置相等,同时前两个int参数并不是圆心而是左上角的坐标,没有自带的circle函数只能自己封装
回到正题:
网上给的都是MouseDown MouseMove MouseUp Paint事件相关的代码,非常的简单。
using System.Drawing; bool bDrawStart = false; Point pointStart = Point.Empty; Point pointContinue = Point.Empty; private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { if (bDrawStart) { bDrawStart = false; } else { bDrawStart = true; pointStart = e.Location; } } private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (bDrawStart) { pointContinue = e.Location; Refresh(); } } private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { if (bDrawStart) { dicPoints.Add(pointStart, pointContinue); } bDrawStart = false; } private void pictureBox1_Paint(object sender, PaintEventArgs e) { if (bDrawStart) { //实时的画矩形 Graphics g = e.Graphics; g.DrawRectangle(pen, pointStart.X, pointStart.Y, pointContinue.X -pointStart.X, pointContinue.Y - pointStart.Y); } pen.Dispose(); }
用完就发现很明显的问题了,一次只能画一个图形
如何才能一次画多个呢?不少都说的重写Paint事件,override之类的函数,多麻烦。
试验修改Paint事件代码即可,定义一个字典表记录画过的矩形(根据对角两个点确定一个矩形,对应字典表的key, value,不考虑矩形相交重叠之类的情况),如下:
Dictionary<Point, Point> dicPoints = new Dictionary<Point, Point>(); private void pictureBox1_Paint(object sender, PaintEventArgs e) { System.Drawing.Pen pen = new System.Drawing.Pen(Color.LimeGreen); pen.Width = 2; if (bDrawStart) { //实时的画矩形 Graphics g = e.Graphics; g.DrawRectangle(pen, pointStart.X, pointStart.Y, pointContinue.X - pointStart.X, pointContinue.Y -pointStart.Y); } //实时的画之前已经画好的矩形 foreach (var item in dicPoints) { Point p1 = item.Key; Point p2 = item.Value; e.Graphics.DrawRectangle(pen, p1.X, p1.Y, p2.X - p1.X, p2.Y - p1.Y); } pen.Dispose(); }