我正在開發一個應用程序來操縱在寬圖像掃描儀上掃描的圖像。這些圖像在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);
}
哦,該死的你!其實這是我嘗試的第一種方法,但我一定做錯了什麼,因爲現在它工作!謝謝 :) –