2015-10-07 63 views
1

我只需要用mousemove在圖片框內繪製一個矩形。 不超過圖片框的邊界。繪製各個方向的矩形

向右或向下拖動對我來說工作正常...如何使moviment反向?

我的代碼如下。

Rectangle Rect = new Rectangle(); 
    private Point RectStartPoint; 
    public Pen cropPen = new Pen(Color.Red, 2); 

    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void pictureBox1_MouseDown(object sender, MouseEventArgs e) 
    { 
     RectStartPoint = e.Location; 
     picImagem.Invalidate(); 
    } 

    private void pictureBox1_MouseMove(object sender, MouseEventArgs e) 
    { 
     if (e.Button == System.Windows.Forms.MouseButtons.Left) 
     { 
      Point tempEndPoint = e.Location; 
      Rect.Location = new Point(Math.Min(RectStartPoint.X, tempEndPoint.X), 
       Math.Min(RectStartPoint.Y, tempEndPoint.Y)); 

      Rect = new Rectangle(
       Math.Min(tempEndPoint.X, Rect.Left), 
       Math.Min(tempEndPoint.Y, Rect.Top), 
       Math.Min(e.X - RectStartPoint.X, picImagem.ClientRectangle.Width - RectStartPoint.X), 
       Math.Min(e.Y - RectStartPoint.Y, picImagem.ClientRectangle.Height - RectStartPoint.Y)); 

      picImagem.Refresh(); 
      picImagem.CreateGraphics().DrawRectangle(cropPen, Rect); 

     } 
    } 
+0

您的確切問題,如下面所回答的,與指定問題完全相同。你的代碼中還有其他錯誤,例如未能捕獲鼠標並使用'CreateGraphics()'來繪製到控件中,而不是處理'Paint'事件或繪製到位圖中。重複的錯誤確實顯示了繪製的正確方法。如果您對其他錯誤有疑問,請提出專門針對這些問題的新問題。 –

+0

另請參閱[此處]的答案(https://stackoverflow.com/a/2529623/3538012)和[此處](https://stackoverflow.com/a/6087367/3538012)以獲取更多靈感。 –

回答

0

您可以糾正你的鼠標移動的代碼是這樣的:

private void pictureBox1_MouseMove(object sender, MouseEventArgs e) 
{ 
    if (e.Button == System.Windows.Forms.MouseButtons.Left) 
    { 
     Point tempEndPoint = e.Location; 

     var point1 = new Point(
      Math.Max(0, Math.Min(RectStartPoint.X, tempEndPoint.X)), 
      Math.Max(0, Math.Min(RectStartPoint.Y, tempEndPoint.Y))); 

     var point2 = new Point(
      Math.Min(this.picImagem.Width, Math.Max(RectStartPoint.X, tempEndPoint.X)), 
      Math.Min(this.picImagem.Height, Math.Max(RectStartPoint.Y, tempEndPoint.Y))); 


     Rect.Location = point1; 
     Rect.Size = new Size(point2.X - point1.X, point2.Y - point1.Y); 


     picImagem.Refresh(); 
     picImagem.CreateGraphics().DrawRectangle(cropPen, Rect); 

    } 
} 

在上面的代碼中,我們首先正常化的開始和矩形的結束,並開始和結束在矩形的邊界。然後我們繪製它。

+0

謝謝你。不錯的工作:) – Pedro

+1

雖然上面解決了你的負矩形問題,但我告誡你,它不能解決代碼中的更大問題:你無法捕獲鼠標(所以如果拖動被窗口焦點改變中斷,用戶可以返回到您的代碼仍然拖動矩形,即使沒有鼠標按鈕),並且您正在使用'CreateGraphics()'完全以錯誤的方式繪製控件__,而不是使控件無效並在「繪製」過程中重繪事件。因此,我不認爲這是一個很好的答案;它只解決了問題中最微不足道的部分。 –

+0

@PeterDuniho你說得對,這段代碼可能還需要做很多事情,但我只解決了關於** Draw Rectangle all directions的問題** –