How to get WinForms PictureBox scaling factor?

I need the exact position of the mouse pointer over the PictureBox.

I am using the MouseMove event for a PictureBox.

On this PictureBox, I use the "zoom" property to display the image.

What is the correct way to get the mouse position on the original (unzoomed) image?

Is there a way to find the scale factor and use it?

It seems to me that I need to use imageOriginalSize / imageShowedSize to extract this scale factor.

I am using this function:

float scaleFactorX = mypic.ClientSize.Width / mypic.Image.Size.Width; float scaleFactorY = mypic.ClientSize.Height / mypic.Image.Size.Height; 

Can this value be used to get the correct cursor position over the image?

+7
source share
2 answers

I had to solve the same problem today. I wanted it to work for images of any width: height ratio.

Here is my method to find the point "unscaled_p" in the original full-size image.

  Point p = pictureBox1.PointToClient(Cursor.Position); Point unscaled_p = new Point(); // image and container dimensions int w_i = pictureBox1.Image.Width; int h_i = pictureBox1.Image.Height; int w_c = pictureBox1.Width; int h_c = pictureBox1.Height; 

The first trick is to determine if the image is horizontal or vertical relative to the container, so you will find out what value of the image fills the container completely.

  float imageRatio = w_i / (float)h_i; // image W:H ratio float containerRatio = w_c / (float)h_c; // container W:H ratio if (imageRatio >= containerRatio) { // horizontal image float scaleFactor = w_c / (float)w_i; float scaledHeight = h_i * scaleFactor; // calculate gap between top of container and top of image float filler = Math.Abs(h_c - scaledHeight) / 2; unscaled_p.X = (int)(pX / scaleFactor); unscaled_p.Y = (int)((pY - filler) / scaleFactor); } else { // vertical image float scaleFactor = h_c / (float)h_i; float scaledWidth = w_i * scaleFactor; float filler = Math.Abs(w_c - scaledWidth) / 2; unscaled_p.X = (int)((pX - filler) / scaleFactor); unscaled_p.Y = (int)(pY / scaleFactor); } return unscaled_p; 

Please note that due to the fact that Zoom centers the image, it is necessary to determine the length of the β€œfiller” in order to determine the size not filled by the image. The result of "unscaled_p" is a point in the unscaled image with which "p" correlates with.

Hope this helps!

+6
source

If I understand you correctly, I believe that you will want to do something like this:

Assumption: PictureBox corresponds to the width / height of the image, there is no space between the border of the PictureBox and the actual image.

 ratioX = eX / pictureBox.ClientSize.Width; ratioY = eY / pictureBox.ClientSize.Height; imageX = image.Width * ratioX; imageY = image.Height * ratioY; 

this should give you points from the pixel in the original image.

+1
source

All Articles