我正在尝试创建一个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();
}
更新2015年6月16日上午12点15分 - 我知道为什么! pictureBox的SizeMode属性设置为StretchImage。将其更改回正常模式,它工作正常。不确定为什么会这样,我肯定会调查它。
对于那些回复的人,非常感谢你的帮助! :)
答案 0 :(得分:2)
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);
}