I have a picture box in a WindowsForms project with its SizeMode to "Zoom".
I want to draw a rectangle inside image and get its coordinates relative to the image and not to the picture box.
The problem is that the rectangle's coordinates do not match with the same rectangle selected on Windows Paint Application.
Here is the code used:
Start Painting:
/// <summary> /// Starts drawing. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void pictureBox1_MouseDown(object sender, MouseEventArgs e) { backupImage = pictureBox1.Image; _once = true; RectStartPoint = e.Location; pictureBox1.Invalidate(); }
While moving mouse:
/// <summary> /// While moving mouse event, paint rectangle /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void pictureBox1_MouseMove(object sender, MouseEventArgs e) { if (_once) //Only draw rectangle while drawing mode { Point tempEndPoint = e.Location; Rect.Location = new Point(Math.Min(RectStartPoint.X, tempEndPoint.X), Math.Min(RectStartPoint.Y, tempEndPoint.Y)); Rect = new Rectangle( Math.Min(tempEndPoint.X, Rect.Left), Math.Min(tempEndPoint.Y, Rect.Top), Math.Min(e.X - RectStartPoint.X, pictureBox1.ClientRectangle.Width - RectStartPoint.X), Math.Min(e.Y - RectStartPoint.Y, pictureBox1.ClientRectangle.Height - RectStartPoint.Y)); pictureBox1.Refresh(); pictureBox1.CreateGraphics().DrawRectangle(cropPen, Rect); } }
When 2 click, finhish painting rectange:
/// <summary> /// When mouse click is released, write in texbox the rectangle's coordinates. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void pictureBox1_MouseUp(object sender, MouseEventArgs e) { if (_once) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { Point tempEndPoint = e.Location; _once = false; string sAux = string.Format("Left: {0}; Top: {1}; Width: {2}; Height: {3} \r\n", Math.Min(tempEndPoint.X, Rect.Left), Math.Min(tempEndPoint.Y, Rect.Top), Math.Min(e.X - RectStartPoint.X, pictureBox1.ClientRectangle.Width - RectStartPoint.X), Math.Min(e.Y - RectStartPoint.Y, pictureBox1.ClientRectangle.Height - RectStartPoint.Y)); textBox1.Text += sAux; } } }
The results are:
Windows Image
Paint Image
As you can see on both images, left, top, width and height do not match.
Can you tell me how to obtain the same result?
Example2