2008-08-05 105 views
13

我有一个应用程序显示Windows窗体内的图像PictureBox控件。该控件的SizeMode设置为Zoom,以便无论PictureBox的尺寸如何,PictureBox中包含的图像都将以方面正确的方式显示。我应该如何从屏幕空间坐标转换为WinForms PictureBox中的图像空间坐标?

这对于应用程序的视觉外观非常棒,因为您可以根据需要调整窗口的大小,并始终使用最适合的方式显示图像。不幸的是,我还需要处理图片框上的鼠标点击事件,并且需要能够从屏幕空间坐标转换为图像空间坐标。

它看起来很容易从屏幕空间转换到控制空间,但我没有看到任何明显的从控制空间转换到图像空间的方式(即源图像中已缩放的像素坐标图片框)。

有没有简单的方法来做到这一点,或者我应该重复他们内部使用的缩放数学来定位图像并自己做翻译?

回答

1

根据缩放比例,相对图像像素可能在许多像素中的任何位置。例如,如果图像显着缩小,像素2,10可以代表2,10直到20,100),所以您必须自己做数学计算,并对任何不准确情况承担全部责任! :-)

6

我结束了手动执行翻译。代码不是太糟糕,但它确实让我希望他们直接提供对它的支持。我可以看到这种方法在很多不同的情况下都很有用。

我想这就是为什么他们增加了扩展方法:)

伪代码:

// 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) 

为了让图像中的像素位置,你只是乘以实际的图像像素尺寸,但规范化的坐标使您可以解决原始响应方关于逐案解决歧义问题的观点。

+1

嗨,很高兴看到你放在一起的代码示例,如果你仍然有它的手。 – 2009-07-30 14:58:53

相关问题