2011-08-24 205 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(); 
    } 

有人能找到這個解決方案的更多有用