2015-10-07 60 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的问题** –