Kel*_*lly 2 .net c# picturebox winforms
我是c#的新手.我在picturebox上有一个图像,我想在图像上绘制一个矩形来捕捉我将绘制的矩形的X,Y坐标和宽度/高度(与图片框上的图像相对).我知道我必须在pictureBox1_MouseEnter..etc上做点什么.但我不知道从哪里开始.
private void pictureBox1_MouseEnter(object sender, EventArgs e)
{
Rectangle Rect = RectangleToScreen(this.ClientRectangle);
}
Run Code Online (Sandbox Code Playgroud)
如果有人能给我示例代码,我将不胜感激.
谢谢.
Cod*_*ray 12
你根本不想使用MouseEnter.您想要使用MouseDown,因为您不希望在用户单击鼠标按钮之后开始跟踪用户绘制的矩形.
所以在MouseDown事件处理程序方法中,保存游标的当前坐标.这是矩形的起始位置,点(X,Y).
private Point initialMousePos;
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
this.initialMousePos = e.Location;
}
Run Code Online (Sandbox Code Playgroud)
然后,在用户停止拖动并释放鼠标按钮时引发的MouseUp事件中,您希望保存鼠标光标的最终结束点,并将其与初始起点组合以构建矩形.构建这样一个矩形的最简单方法是使用该类的FromLTRB静态方法:Rectangle
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
// Save the final position of the mouse
Point finalMousePos = e.Location;
// Create the rectangle from the two points
Rectangle drawnRect = Rectangle.FromLTRB(
this.initialMousePos.X,
this.initialMousePos.Y,
finalMousePos.X,
finalMousePos.Y);
// Do whatever you want with the rectangle here
// ...
}
Run Code Online (Sandbox Code Playgroud)
您可能希望将此与MouseMove事件处理程序方法中的一些绘制代码结合使用,以便为用户提供他们在绘制时绘制的矩形的可视指示.
在正确的做到这一点的办法是处理MouseMove事件得到鼠标的当前位置,然后调用Invalidate方法,这将提高该Paint事件.您的所有绘图代码都应该在Paint事件处理程序中.这是一种比在网络上找到的大量样本所采用的方法更好的方法,在这种方法中,您将看到CreateGraphics在MouseMove事件处理程序方法内部调用的内容.如果可能,请避免这样做.
示例实施:
private Point currentMousePos;
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
// Save the current position of the mouse
currentMousePos = e.Location;
// Force the picture box to be repainted
pictureBox1.Invalidate();
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
// Create a pen object that we'll use to draw
// (change these parameters to make it any color and size you want)
using (Pen p = new Pen(Color.Blue, 3.0F))
{
// Create a rectangle with the initial cursor location as the upper-left
// point, and the current cursor location as the bottom-right point
Rectangle currentRect = Rectangle.FromLTRB(
this.initialMousePos.X,
this.initialMousePos.Y,
currentMousePos.X,
currentMousePos.Y);
// Draw the rectangle
e.Graphics.DrawRectangle(p, currentRect);
}
}
Run Code Online (Sandbox Code Playgroud)
如果你之前从未做过任何类型的绘图,那么有关这段代码的几点注意事项.第一件事是我在一个语句中包装了一个Pen对象(我们用来做实际绘图)的创建.每次创建实现接口的对象(例如画笔和笔)时,这都是很好的通用做法,以防止应用程序中的内存泄漏. usingIDisposable
另外,PaintEventArgs为我们提供了一个Graphics类的实例,它封装了.NET应用程序中的所有基本绘图功能.所有你所要做的就是调用方法类似DrawRectangle或DrawImage在该类的实例,通过在适当的对象作为参数,而所有的图纸被自动完成的.很简单吧?
最后,请注意我们在这里做了完全相同的事情来创建一个矩形,就像我们最终在MouseUp事件处理程序方法中做的那样.这是有道理的,因为我们只想在用户创建矩形时获得矩形的瞬时大小.