c# PictureBox 的图像上使用鼠标画矩形框

C# 中在图像上画框,通过鼠标来实现主要有四个消息响应函数MouseDown, MouseMove, MouseUp, Paint重绘函数实现。当鼠标键按下时开始画框,鼠标键抬起时画框结束。

?
1
2
Point start; //画框的起始点
Point end,//画框的结束点<br>bool blnDraw;//判断是否绘制<br>Rectangel rect;

鼠标按下响应

?
1
2
3
4
5
6
private void PictureBox1_MouseDown(object sender, MouseEventArgs e)
{
      start = e.Location;
      Invalidate();
      blnDraw = true;
}

鼠标移动响应 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private void PictureBox1_MouseMove(object sender, MouseEventArgs e)
{
    if (blnDraw)
    {
        if (e.Button != MouseButtons.Left)//判断是否按下左键
            return;
        Point tempEndPoint = e.Location; //记录框的位置和大小
        rect.Location = new Point(
        Math.Min(start.X, tempEndPoint.X),
        Math.Min(start.Y, tempEndPoint.Y));
        rect.Size = new Size(
        Math.Abs(start.X - tempEndPoint.X),
        Math.Abs(start.Y - tempEndPoint.Y));
        PictureBox1.Invalidate();
     }
}       

鼠标键抬起响应

?
1
2
3
4
private void PictureBox1_MouseUp(object sender, MouseEventArgs e)
 {
    blnDraw = false; //结束绘制
 }

重绘响应

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
private void imageBox1_Paint(object sender, PaintEventArgs e)
{
     if (blnDraw)
     {
         if (imageBox1.Image != null)
         {
             if (rect != null && rect.Width > 0 && rect.Height > 0)
              {
                  e.Graphics.DrawRectangle(new Pen(Color.Red, 3),rect);//重新绘制颜色为红色
               }
          }
      }
}

注意:在绘制中如果导入的图像的SizeMode为StretchImage时,画框后图像会缩放,导致框有可能不在pictureBox中,需要将PictureBox的FunctionMode 修改为Minimum 便可。

(0)

相关推荐