c#在pictureBox控件上绘制多个矩形框及删除绘制的矩形框
程序员文章站
2022-03-23 19:08:03
在pictureBox上每次只绘制一个矩形框,绘制下一个矩形框时上次绘制的矩形框取消,代码如链接:https://www.cnblogs.com/luxiao/p/5625196.html 在绘制矩形框时要在程序中添加鼠标相应的事件MouseDown、MouseUp、MouseMove、Paint。 ......
在picturebox上每次只绘制一个矩形框,绘制下一个矩形框时上次绘制的矩形框取消,代码如链接:https://www.cnblogs.com/luxiao/p/5625196.html
在绘制矩形框时要在程序中添加鼠标相应的事件mousedown、mouseup、mousemove、paint。
绘制矩形框的代码如下:
1 point start, end;//绘制矩形框的起点和终点 2 bool blndraw;//在mousemove事件中判断是否绘制矩形框 3 public struct startandendpoint 4 { 5 point start; 6 point end; 7 } 8 //绘制矩形起始点和终止点的集合 9 list<startandendpoint> multiareapoint=new list<startandendpoint>(); 10 11 private void pic_mousedown(object sender, mouseeventargs e) 12 { 13 if (e.button == mousebuttons.left) 14 { 15 start = e.location; 16 blndraw = true; 17 } 18 // 点击鼠标右键绘制整个picturebox区域 19 if (e.button == mousebuttons.right) 20 { 21 start = new point(0, 0); 22 } 23 } 24 25 private void pic_mouseup(object sender, mouseeventargs e) 26 { 27 picturebox pic = sender as picturebox; 28 29 if (e.button == mousebuttons.left) 30 { 31 end = e.location; 32 blndraw = false; 33 } 34 if (e.button == mousebuttons.right) 35 { 36 end = new point(pic.width, pic.height); 37 } 38 39 40 if (pic.image != null) 41 { 42 if (start != end) 43 { 44 startandendpoint onepoint = new startandendpoint(); 45 onepoint.start = start; 46 onepoint.end = end; 47 48 if ((!multiareapoint.contains(onepoint))) 49 { 50 multiareapoint.add(onepoint);//添加不同区域起始和终止点的结构体数组 51 } 52 } 53 } 54 55 //pic.refresh(); 56 } 57 58 private void pic_mousemove(object sender, mouseeventargs e) 59 { 60 if (blndraw) 61 { 62 if (e.button != mousebuttons.left)//判断是否按下左键 63 return; 64 end = e.location; 65 pic.invalidate(); 66 } 67 }
1 private void pic_paint(object sender, painteventargs e) 2 { 3 picturebox pic = sender as picturebox; 4 5 pen pen = new pen(color.red, 1); 6 pen.dashstyle = system.drawing.drawing2d.dashstyle.dot;//绘制线的格式 7 if (blndraw) 8 { 9 if (pic.image != null) 10 { 11 //此处是为了在绘制时可以由上向下绘制,也可以由下向上绘制 12 e.graphics.drawrectangle(pen, math.min(start.x, end.x), math.min(start.y, end.y), math.abs(start.x - end.x), math.abs(start.y - end.y)); 13 } 14 } 15 16 //将之前绘制的矩形框再次绘制一遍 17 foreach (startandendpoint points in multiareapoint) 18 { 19 point p1 = points.start; 20 point p2 = points.end; 21 e.graphics.drawrectangle(pen, math.min(p1.x, p2.x), math.min(p1.y, p2.y), math.abs(p1.x - p2.x), math.abs(p1.y - p2.y)); 22 } 23 24 pen.dispose(); 25 }
多个矩形框绘制相对于绘制单个矩形框而言不能自动取消掉上一次的绘制了,那么如何取消绘制在picturebox上的矩形框呢?
绘制多个矩形框的原理是将多个起始点与终止点放到数组中,在调用paint方法时,将这些点重新绘制一遍,那么取消绘制这些矩形就可以将数组中的点删除掉,在调用paint方法就可以删除这些矩形啦!
代码如下:
1 multiareapoint.clear(); 2 pic.refresh();
pic.refresh();是为了调用paint方法。
若有不同见解或其他实现方法,欢迎与我交流。