我正在尝试创建Windows窗体应用程序,其中,当用户单击图片框上的任意位置时,在单击图像的位置会出现一个矩形。
但是,如果我单击图像上的任意位置,则无论单击何处,矩形都会出现在某个随机位置。它可以出现在鼠标单击附近或远离鼠标单击的位置,在某些情况下,它永远不会超出图片框的左半部分。
我可以就如何解决此问题提供一些指导吗?具体来说,我希望单击的位置是矩形的中心。
谢谢!
这是我的代码供参考:
private void pbImage_Click(object sender, EventArgs e)
{
//Note: pbImage is the name of the picture box used here.
var mouseEventArgs = e as MouseEventArgs;
int x = mouseEventArgs.Location.X;
int y = mouseEventArgs.Location.Y;
// We first cast the "Image" property of the pbImage picture box control
// into a Bitmap object.
Bitmap pbImageBitmap = (Bitmap)(pbImage.Image);
// Obtain a Graphics object from the Bitmap object.
Graphics graphics = Graphics.FromImage((Image)pbImageBitmap);
Pen whitePen = new Pen(Color.White, 1);
// Show the coordinates of the mouse click on the label, label1.
label1.Text = "X: " + x + " Y: " + y;
Rectangle rect = new Rectangle(x, y, 200, 200);
// Draw the rectangle, starting with the given coordinates, on the picture box.
graphics.DrawRectangle(whitePen, rect);
// Refresh the picture box control in order that
// our graphics operation can be rendered.
pbImage.Refresh();
// Calling Dispose() is like calling the destructor of the respective object.
// Dispose() clears all resources associated with the object, but the object still remains in memory
// until the system garbage-collects it.
graphics.Dispose();
}
UPDATE 12.55am,16/8/2015-我知道为什么!pictureBox的SizeMode属性设置为StretchImage。将其更改回普通模式,并且工作正常。不确定为什么会这样,我一定会调查一下。
对于那些回答过的人,非常感谢您的帮助!:)
Rectangle构造函数的前两个参数是左上角(而不是中心)坐标。
并分别处理鼠标和绘画事件:
int mouseX, mouseY;
private void pbImage_MouseDown(object sender, MouseEventArgs e)
{
mouseX = e.X;
mouseY = e.Y;
pbImage.Refresh();
}
private void pbImage_Paint(object sender, PaintEventArgs e)
{
//... your other stuff
Rectangle rect = new Rectangle(mouseX - 100, mouseY - 100, 200, 200);
e.Graphics.DrawRectangle(whitePen, rect);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句