在PictureBox上绘制矩形 - 如何限制矩形的区域?

5
我正在使用鼠标事件在PictureBox上绘制矩形:
private void StreamingWindow_MouseDown(object sender, MouseEventArgs e)
    {
              rect = new Rectangle(e.X, e.Y, 0, 0);
              this.Invalidate();       
    }

    private void StreamingWindow_Paint(object sender, PaintEventArgs e)
    {

       if (painting == true)
        {

            using (Pen pen = new Pen(Color.Red, 2))
            {
                e.Graphics.DrawRectangle(pen, rect);
            }
        }
    }

    private void StreamingWindow_MouseMove(object sender, MouseEventArgs e)
    {       
           if (e.Button == MouseButtons.Left)
           {
               // Draws the rectangle as the mouse moves
               rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y - rect.Top);
           }
           this.Invalidate();     
    }

绘制矩形后,我可以捕获其中的内容,并保存为jpg格式。
我的问题是什么?
我可以绘制边框超出picturebox区域的矩形:
enter image description here
如何限制矩形区域,使得picturebox边框是矩形的最大允许位置?
抱歉我的英语不好,但我希望你能理解我的问题 :)
因此,我的期望结果是这样的:
enter image description here
4个回答

2
private void StreamingWindow_MouseMove(object sender, MouseEventArgs e)
{       
  if (e.Button == MouseButtons.Left)
  {
    // Draws the rectangle as the mouse moves
    rect = new Rectangle(rect.Left, rect.Top, Math.Min(e.X - rect.Left, pictureBox1.ClientRectangle.Width - rect.Left), Math.Min(e.Y - rect.Top, pictureBox1.ClientRectangle.Height - rect.Top));
  }
  this.Invalidate();     
}

我以为这会更加复杂 ;) - Elfoc

0

我认为从UX角度来看,实现这一点最简单的方法,也是我个人认为更自然的方法是:在MouseUp之后检查矩形的BottomLeft角是否在图片框的区域之外,如果是,则将其“带回来”,并将其与图片框的角度对齐就像你画的那样

编辑

只是为了让您了解我在谈论什么,这是一个伪代码

    private void StreamingWindow_MouseUp(object sender, MouseEventArgs e)
    {
              if(rect.Right > myPictureBox.ClientRectangle.Right)
              {
                 rect.Width = myPictureBox.Right - rect.Left - someoffset;                     
              }       
              if(rect.Bottom > myPictureBox.ClientRectangle.Bottom)
              {
                 rect.Height= myPictureBox.Bottom - rect.Top - someoffset;                     
              }       
    }

这样的东西。但你需要检查一下。


也许有一点提示如何做到这一点?这将与http://msdn.microsoft.com/en-us/library/system.windows.rect.bottomleft.aspx相关联,我是对的吗? - Elfoc

0
为什么不将矩形坐标设置为某个值呢?
 rect = new Rectangle(min(e.X, pictureBoxX), min(e.Y, pictureBoxY), 0, 0);

根据图片框的位置和位置,您需要计算pictureX和pictureY。


0
另一种解决方法是防止矩形在pictureBox控件之外绘制。
private void StreamingWindow_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            if (e.X < StreamingWindow.Width && Math.Abs(e.Y) < StreamingWindow.Height)
                // Draws the rectangle as the mouse moves
                rect = new Rectangle(rect.Left, rect.Top, e.X - rect.Left, e.Y -rect.Top);
        }
        this.Invalidate();
    }

有些人可能会发现这个解决方案更有用


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接