Here is a function to help with various calculations:
void SetImageScale(PictureBox pbox, out RectangleF ImgArea, out float zoom)
{
SizeF sp = pbox.ClientSize;
SizeF si = pbox.Image.Size;
float rp = sp.Width / sp.Height; // calculate the ratios of
float ri = si.Width / si.Height; // pbox and image
if (rp > ri)
{
zoom = 1f * sp.Height / si.Height;
float width = si.Width * zoom;
float left = (sp.Width - width) / 2;
ImgArea = new RectangleF(left, 0, width, sp.Height);
}
else
{
zoom = 1f * sp.Width / si.Width;
float height = si.Height * zoom;
float top = (sp.Height - height) / 2;
ImgArea = new RectangleF(0, top, sp.Width, height);
}
}
Here is how you can use it, given a Rectangle Rect
which you created from the mouse coordinates:
float zoom = 1f;
RectangleF ImgArea = Rectangle.Empty;
SetImageScale(pictureBox1, out ImgArea, out zoom);
Point RLoc = Point.Round(new PointF( (Rect.X - ImgArea.X) / zoom,
(Rect.Y - ImgArea.Y) / zoom ));
Size RSz = Size.Round(new SizeF(Rect.Width / zoom, Rect.Height / zoom));
label1.Text = "Selection in mouse coordinates: " + Rect.ToString();
label2.Text = "Selection in image coordinates: " + new Rectangle(RLoc, RSz).ToString();
This should work no matter whether the images are landscape or portrait or which ratio if any is greater, the Image's or the PictureBox's.
Note that with the images strongly zoomed it is hard to do a pixel-pefect selection..
The function is variant of the one in this post.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…