2012-09-27 34 views
1

我正在開發一個應用程序來操縱在寬圖像掃描儀上掃描的圖像。這些圖像在Canvas上顯示爲ImageBrush。 在這個Canvas他們可以用鼠標製作Rectangle來定義一個要裁剪的區域。調整繪製的矩形以適應原始圖像

這裏我的問題是根據原始圖像大小調整Rectangle的大小,以便裁剪原始圖像上的確切區域。

到目前爲止,我已經嘗試了很多東西,它只是用我的大腦來找出正確的解決方案。
我知道我需要得到原始圖像比畫布上顯示的圖像更大的百分比。

原始圖像的dimentions爲:

H:5606
寬:7677

當我顯示圖像,它們分別是:

h:1058,04
w:1910

其中給出這些數字:

float percentWidth = ((originalWidth - resizedWidth)/originalWidth) * 100; 
float percentHeight = ((originalHeight - resizedHeight)/originalHeight) * 100; 

percentWidth = 75,12049 
percentHeight = 81,12665 

在這裏,我找不出如何正確調整Rectangle,以適應原始圖像。

我最後的辦法是這樣的:

int newRectWidth = (int)((originalWidth * percentWidth)/100); 
int newRectHeight = (int)((originalHeight * percentHeight)/100); 
int newRectX = (int)(rectX + ((rectX * percentWidth)/100)); 
int newRectY = (int)(rectY + ((rectY * percentHeight)/100)); 

希望有人會導致我在正確的方向,因爲我偏離軌道的在這裏,我不能看見我錯過了什麼。

解決方案

private System.Drawing.Rectangle FitRectangleToOriginal(
     float resizedWidth, 
     float resizedHeight, 
     float originalWidth, 
     float originalHeight, 
     float rectWidth, 
     float rectHeight, 
     double rectX, 
     double rectY) 
    { 
     // Calculate the ratio between original and resized image 
     float ratioWidth = originalWidth/resizedWidth; 
     float ratioHeight = originalHeight/resizedHeight; 

     // create a new rectagle, by resizing the old values 
     // by the ratio calculated above 
     int newRectWidth = (int)(rectWidth * ratioWidth); 
     int newRectHeight = (int)(rectHeight * ratioHeight); 
     int newRectX = (int)(rectX * ratioWidth); 
     int newRectY = (int)(rectY * ratioHeight); 

     return new System.Drawing.Rectangle(newRectX, newRectY, newRectWidth, newRectHeight); 
    } 

回答

1

你實際上正在做一種投影形式。不要使用百分比,只是使用5606和1058,4 = 5.30之間的比率。當用戶拖動矩形時,重新投影它,即selectedWidth * 5606/1058.4

+0

哦,該死的你!其實這是我嘗試的第一種方法,但我一定做錯了什麼,因爲現在它工作!謝謝 :) –

2

我認爲唯一可靠的選擇是讓你的用戶放大的圖像(100%或更高的縮放級別),並在圖像的一部分的選擇。這樣他們可以做出精確的基於像素的選擇。 (假設您的選擇矩形的目的是選擇圖像的一部分。)

您現在的問題是您使用浮點計算,因爲75%縮放級別和舍入錯誤會使您的選擇矩形不準確的。不管你做什麼,當你嘗試在縮小的圖像上做出選擇時,你都不會選擇確切的像素 - 當你調整矩形的大小時,你正在選擇像素的一部分。由於無法選擇部分像素,所以選擇邊將向上舍入或向下舍入,因此您要麼在給定方向上選擇一個像素太多,要麼選擇一個像素太少。

我剛剛注意到的另一個問題是,您扭曲了圖像 - 水平方向爲75%,垂直方向爲81%。這對用戶來說更加困難,因爲圖像在兩個方向上將被平滑化。水平4個原始像素將被插值在3個輸出像素上;垂直5個原始像素將被插值在4個輸出像素上。

+0

實際上很好讀,即使這不能解決我的問題。但是,這隻會導致由ranieuwe給出的觀點/回答...從這裏計算圖像寬度/高度+1時不要使用procent :) –

+0

@JesperJensen謝謝 - 我很高興您的問題已解決。 – xxbbcc