我试图创建一个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时55分,16/8/2015 - 我知道为什么! pictureBox的SizeMode属性设置为StretchImage。改回到正常模式,它工作正常。不完全确定为什么这样,我一定会研究它。
对于已回复的人,非常感谢您的帮助! :)