如何“智能调整大小"显示的图像与原始纵横比

问题描述:

我有一个应用程序,最终用户可以在其中在设计器中调整图像的大小和位置.由于规范要求将图像拉伸"到包含控件,因此最终用户可能会得到一个笨拙的拉伸图像.

I have an application in which end-users can size and position images in a designer. Since the spec calls for the image to be "stretched" to the containing control, the end user can end up with an awkwardly stretched image.

为了帮助用户调整图像大小,我正在考虑实现一个智能调整器功能,该功能允许用户轻松固定图片的纵横比,使其不再显得拉伸.

To help the user with image sizing I am thinking of implementing a smart resizer function which would allow the the user to easily fix the aspect ratio of the picture so that it no longer appears stretched.

解决这个问题的快速方法实际上是提供两个选项:1) 从宽度缩放 2) 从高度缩放.用户选择方法,算法使用原始纵横比调整图片大小.例如:一张图片在设计器上显示为 200x200,但原始图像是 1024x768 像素.用户选择Smart Size from width",新尺寸变为~200x150,因为原来的纵横比是~1.333

The quick way to solve this is to actually provide two options: 1) scale from width 2) scale from height. The user chooses the method and the algorithm adjusts the size of the picture by using the original aspect ratio. For example: A picture is displayed as 200x200 on the designer but the original image is 1024x768 pixels. The user chooses "Smart Size from width" and the new size becomes ~200x150 since the original aspect ratio is ~1.333

没关系,但是我怎样才能使算法更智能,并且不会通过询问重新计算应该基于哪个维度来打扰用户?

That's OK, but how could I make the algorithm smarter and not bother the user by asking which dimension the recalculation should be based on?

如果我正确解释了您的规范,您希望得到的结果不大于最终用户最初布置的结果;您希望两个维度中的一个缩小,另一个保持不变.换句话说,新尺寸应该在一个方向填充设计器空间,同时在另一个方向缩短尺寸以保持原始纵横比.

If I'm interpreting your spec correctly, you want a result that is no larger than the one the end-user laid out originally; you want one of the two dimensions to shrink, and the other to stay the same. In other words, the new size should fill the designer space in one direction while shortening the size in the other direction to retain the original aspect ratio.

original_ratio = original_width / original_height
designer_ratio = designer_width / designer_height
if original_ratio > designer_ratio
    designer_height = designer_width / original_ratio
else
    designer_width = designer_height * original_ratio

通常您会使用整数坐标,但产生上述比率的除法需要是浮点数.这是对公式的重新排列,使其对整数更友好.确保您的整数具有处理最大宽度*高度的范围.

Often you'll be working with integer coordinates, but the divisions to produce the ratios above need to be floating point. Here's a rearrangement of the formula to be more integer friendly. Make sure your integers have the range to handle the maximum width*height.

if original_width * designer_height > designer_width * original_height
    designer_height = (designer_width * original_height) / original_width
else
    designer_width = (designer_height * original_width) / original_height