2011-08-24 206 views
5

我对图片框绘制矩形与鼠标事件:在图框上绘制矩形 - 如何限制矩形区域?

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格式后。

我的问题是什么?

我可以得出retangle接壤的图片框的外侧区域:

enter image description here

我怎么能限制图片框的边框允许最大矩形的位置矩形的面积?

对不起,我的英语,我希望你能理解我的问题:) 因此,作为一个结果,我想有这样的事情:

enter image description here

回答

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();  
} 
+0

我认为它会复杂得多;) – 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;      
       }  
    } 

这样的事情。但你需要检查这一点。

+0

也许小提示如何做到这一点?它将与http://msdn.microsoft.com/en-us/library/system.windows.rect.bottomleft.aspx连接,对吗? – Elfoc

+0

@Elfoc看到我编辑的文章 – Tigran

0

为什么不矩型座标设置您需要根据图片框的位置和定位计算pictureX和pictureY东西

rect = new Rectangle(min(e.X, pictureBoxX), min(e.Y, pictureBoxY), 0, 0); 

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(); 
    } 

有人能找到这个解决方案的更多有用