2012-09-27 33 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