2011-08-24 14 views
5

私はマウスイベントでのPictureBoxに四角形を描画しています: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として保存します。

私の問題は何ですか?どのように私は、ピクチャボックスの境界線が長方形の最大許可された場所である長方形の面積を制限することができ

enter image description here

私は国境がピクチャボックスの外側の領域ですretangleを描くことができますか?私の英語のため申し訳ありません

、私はあなたが私の問題を理解していただければ幸いです:) ので、結果として、私はこのような何かしたいのですが:

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矩形のコーナーがピクチャボックスの領域の外にある場合は、それを "戻し"てピクチャボックスの角度と同じようにを入力してください。このような

EDIT

ただ、あなたに私が話して何のアイデアを与えるために、擬似コード

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

たぶん少しヒントをもっと便利この解決策を見つけることができPictureBoxコントロールの外に溺れしますか?それは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); 

にするRECT COORDSを設定していません。

0

この防止される矩形を解決するための別の方法は

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

誰かがこれを行う方法を

関連する問題