Given the height and the width of a rectangle of any size and an aspect ratio, how can I calculate the height and width of a minimum enclosing rectangle of the given aspect ratio?
给定任意大小和纵横比的矩形的高度和宽度,如何计算给定纵横比的最小包围矩形的高度和宽度?
In code, the function signature would look like this
在代码中,函数签名看起来像这样
public Size getMinimumEnclosingRectangle(Size originalRectangle, float aspectNumerator, float aspectDenomiator);
Calls to this function would look like
调用此函数看起来像
originalRectangle AspectRatio Result
-------------------------------------------
100x100 1:2 100x200
64x32 1:1 64x64
125x100 3:2 150x100
100x345 1:3 115x345
1 个解决方案
#1
This may not be the best way, but the way I do this calculation is to calculate the change in aspect ratio and then base the resulting width/height calculation of of that. Here is some code to illustrate this algorithm in practice:
这可能不是最好的方法,但我进行此计算的方法是计算纵横比的变化,然后根据结果的宽度/高度计算。以下是一些在实践中说明此算法的代码:
var sourceImages = [
{width: 100, height: 100, toAspectRatio:1/2 },
{width: 64, height: 32, toAspectRatio:1/1 },
{width: 125, height: 100, toAspectRatio:3/2 },
{width: 100, height: 345, toAspectRatio:1/3 },
{width: 345, height: 100, toAspectRatio:1/3 }
];
function calculateNewSize( sourceWidth, sourceHeight, toAspectRatio )
{
var aspectRatioChange = (sourceWidth / sourceHeight) / toAspectRatio;
var fitWidth = aspectRatioChange < 1 ? sourceHeight * toAspectRatio : sourceWidth;
var fitHeight = aspectRatioChange >= 1 ? sourceWidth / toAspectRatio : sourceHeight;
console.log('(' + aspectRatioChange + ') ' + sourceWidth + " x " + sourceHeight + " -> "
+ toAspectRatio + ' -> ' + fitWidth + ' x ' + fitHeight);
}
sourceImages.forEach(function(source) {
calculateNewSize(source.width, source.height, source.toAspectRatio);
});
#1
This may not be the best way, but the way I do this calculation is to calculate the change in aspect ratio and then base the resulting width/height calculation of of that. Here is some code to illustrate this algorithm in practice:
这可能不是最好的方法,但我进行此计算的方法是计算纵横比的变化,然后根据结果的宽度/高度计算。以下是一些在实践中说明此算法的代码:
var sourceImages = [
{width: 100, height: 100, toAspectRatio:1/2 },
{width: 64, height: 32, toAspectRatio:1/1 },
{width: 125, height: 100, toAspectRatio:3/2 },
{width: 100, height: 345, toAspectRatio:1/3 },
{width: 345, height: 100, toAspectRatio:1/3 }
];
function calculateNewSize( sourceWidth, sourceHeight, toAspectRatio )
{
var aspectRatioChange = (sourceWidth / sourceHeight) / toAspectRatio;
var fitWidth = aspectRatioChange < 1 ? sourceHeight * toAspectRatio : sourceWidth;
var fitHeight = aspectRatioChange >= 1 ? sourceWidth / toAspectRatio : sourceHeight;
console.log('(' + aspectRatioChange + ') ' + sourceWidth + " x " + sourceHeight + " -> "
+ toAspectRatio + ' -> ' + fitWidth + ' x ' + fitHeight);
}
sourceImages.forEach(function(source) {
calculateNewSize(source.width, source.height, source.toAspectRatio);
});