我試圖創建一個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。改回到正常模式,它工作正常。不完全確定爲什麼這樣,我一定會研究它。
對於已回覆的人,非常感謝您的幫助! :)