How to retrieve zoom factor of a WinForms PictureBox?
我需要鼠标指针在图片框上的精确位置。
我使用 PictureBox 的 MouseMove 事件。
在这个 PictureBox 上,我使用 "zoom" 属性来显示图像。
在原始(未缩放)图像上获取鼠标位置的正确方法是什么?
有没有办法找到比例因子并使用它?
我认为需要使用 imageOriginalSize/imageShowedSize 来检索这个比例因子。
我使用这个功能:
1 2 | float scaleFactorX = mypic.ClientSize.Width / mypic.Image.Size.Width; float scaleFactorY = mypic.ClientSize.Height / mypic.Image.Size.Height; |
是否可以使用这个值来获得光标在图像上的正确位置?
我今天必须解决同样的问题。我希望它适用于任何宽高比的图像。
这是我在原始全尺寸图像上找到点 \\'unscaled_p\\' 的方法。
1 2 3 4 5 6 7 8 | 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; |
第一个技巧是确定图像相对于容器在水平方向还是垂直方向上更大,这样您就可以知道哪个图像尺寸完全填满了容器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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)(p.X / scaleFactor); unscaled_p.Y = (int)((p.Y - 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)((p.X - filler) / scaleFactor); unscaled_p.Y = (int)(p.Y / scaleFactor); } return unscaled_p; |
请注意,由于 Zoom 使图像居中,因此必须将 \\'filler\\' 长度考虑在内,以确定未由图像填充的尺寸。结果 \\'unscaled_p\\' 是未缩放图像上与 \\'p\\' 相关的点。
希望有帮助!
如果我对你的理解正确,我相信你会想做这样的事情:
假设:图片框适合图片的宽/高,图片框的边框和实际图片之间没有空间。
1 2 3 4 5 | ratioX = e.X / pictureBox.ClientSize.Width; ratioY = e.Y / pictureBox.ClientSize.Height; imageX = image.Width * ratioX; imageY = image.Height * ratioY; |
这应该给你原始图像中的像素点。