
How should I translate from screen space coordinates to image space coordinates in a WinForms PictureBox?
我有一个在 Windows 窗体 PictureBox 控件中显示图像的应用程序。控件的 SizeMode 设置为 Zoom 以便在 PictureBox 中包含的图像将以正确的方式显示,而与 PictureBox 的尺寸无关。
这对于应用程序的视觉外观非常有用,因为您可以根据需要调整窗口大小,并且始终以最适合的方式显示图像。不幸的是,我还需要处理图片框上的鼠标单击事件,并且需要能够从屏幕空间坐标转换为图像空间坐标。
看起来从屏幕空间转换到控制空间很容易,但我没有看到任何明显的从控制空间转换到图像空间的方法(即源图像中的像素坐标)在图片框中缩放)。
有没有一种简单的方法可以做到这一点,还是我应该复制他们在内部使用的缩放数学来定位图像并自己进行翻译?
我最终只是手动实现了翻译。代码还不错,但它确实让我希望他们直接为它提供支持。我可以看到这种方法在很多不同的情况下都很有用。
我猜这就是他们添加扩展方法的原因:)
在伪代码中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| // Recompute the image scaling the zoom mode uses to fit the image on screen
imageScale ::= min(pictureBox.width / image.width, pictureBox.height / image.height)
scaledWidth ::= image.width * imageScale
scaledHeight ::= image.height * imageScale
// Compute the offset of the image to center it in the picture box
imageX ::= (pictureBox.width - scaledWidth) / 2
imageY ::= (pictureBox.height - scaledHeight) / 2
// Test the coordinate in the picture box against the image bounds
if pos.x imageX or imageX + scaledWidth pos.x then return null
if pos.y imageY or imageY + scaledHeight pos.y then return null
// Compute the normalized (0..1) coordinates in image space
u ::= (pos.x - imageX) / imageScale
v ::= (pos.y - imageY) / imageScale
return (u, v) |
要获得图像中的像素位置,您只需乘以实际图像像素尺寸,但归一化坐标允许您解决原始响应者关于逐案解决歧义的观点基础。
根据缩放比例,相对图像像素可以是多个像素中的任意位置。例如,如果图像被显着缩小,像素 2、10 可能代表 2、10 一直到 20、100),因此您必须自己进行数学运算并对任何不准确承担全部责任! :-)
|
空间屏幕图像空间控件
免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。