在pictureBox上每次只绘制一个矩形框,绘制下一个矩形框时上次绘制的矩形框取消,代码如链接:https://www.cnblogs.com/luxiao/p/5625196.html
在绘制矩形框时要在程序中添加鼠标相应的事件MouseDown、MouseUp、MouseMove、Paint。
绘制矩形框的代码如下:
Point start, end;//绘制矩形框的起点和终点
bool blnDraw;//在MouseMove事件中判断是否绘制矩形框
public struct StartAndEndPoint
{
Point Start;
Point End;
}
//绘制矩形起始点和终止点的集合
List<StartAndEndPoint> multiAreaPoint=new List<StartAndEndPoint>(); private void pic_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
start = e.Location;
blnDraw = true;
}
// 点击鼠标右键绘制整个pictureBox区域
if (e.Button == MouseButtons.Right)
{
start = new Point(, );
}
} private void pic_MouseUp(object sender, MouseEventArgs e)
{
PictureBox pic = sender as PictureBox; if (e.Button == MouseButtons.Left)
{
end = e.Location;
blnDraw = false;
}
if (e.Button == MouseButtons.Right)
{
end = new Point(pic.Width, pic.Height);
} if (pic.Image != null)
{
if (start != end)
{
StartAndEndPoint onepoint = new StartAndEndPoint();
onepoint.start = start;
onepoint.end = end; if ((!multiAreaPoint.Contains(onepoint)))
{
multiAreaPoint.Add(onepoint);//添加不同区域起始和终止点的结构体数组
}
}
} //pic.Refresh();
} private void pic_MouseMove(object sender, MouseEventArgs e)
{
if (blnDraw)
{
if (e.Button != MouseButtons.Left)//判断是否按下左键
return;
end = e.Location;
pic.Invalidate();
}
}
private void pic_Paint(object sender, PaintEventArgs e)
{
PictureBox pic = sender as PictureBox; Pen pen = new Pen(Color.Red, );
pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;//绘制线的格式
if (blnDraw)
{
if (pic.Image != null)
{
//此处是为了在绘制时可以由上向下绘制,也可以由下向上绘制
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));
}
} //将之前绘制的矩形框再次绘制一遍
foreach (StartAndEndPoint points in multiAreaPoint)
{
Point p1 = points.start;
Point p2 = points.end;
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));
} pen.Dispose();
}
多个矩形框绘制相对于绘制单个矩形框而言不能自动取消掉上一次的绘制了,那么如何取消绘制在pictureBox上的矩形框呢?
绘制多个矩形框的原理是将多个起始点与终止点放到数组中,在调用Paint方法时,将这些点重新绘制一遍,那么取消绘制这些矩形就可以将数组中的点删除掉,在调用Paint方法就可以删除这些矩形啦!
代码如下:
multiAreaPoint.Clear();
pic.Refresh();
pic.Refresh();是为了调用Paint方法。
若有不同见解或其他实现方法,欢迎与我交流。