2008-08-05 103 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

相關問題