C#之在PictureBox上绘制动态矩形框
多次做项目都用到了画ROI区域,简单来说就是在PictureBox上画矩形区域,特写此博文以方便日后查阅。
在PictureBox上画矩形主要利用了以下几个事件:
1、MouseDown事件
Point start; //起始点
Point end; //结束点
bool blnDraw; //在MouseMove事件中判断是否绘制矩形框
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
start = e.Location;
blnDraw = true;
}
}
2、MouseMove事件
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (blnDraw)
{
if (e.Button != MouseButtons.Left) return;
end = e.Location;
pictureBox1.Invalidate();//此代码不可省略
}
}
3、MouseUp事件
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
endPoint = e.Location;
blnDraw = false;
}
}
4、Paint事件
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
PictureBox pic = sender as PictureBox;
Pen pen = new Pen(Color.Red, 3);
pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot; //绘制线的格式
if (blnDraw)
{
//此处是为了在绘制时可以由上向下绘制,也可以由下向上
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));
}
pen.Dispose();
}