function gcd(a, b) {
return (b == 0) ? a : gcd(b, a % b);
}
你应该做这样的事情:
function calcRatio(objectWidth, objectHeight) {
var ratio = gcd(objectWidth, objectHeight),
xRatio = objectWidth / ratio,
yRatio = objectHeight / ratio;
return { "x": xRatio, "y": yRatio };
}
这将获得一些对象的比例 . 您可以使用此信息来确定生成的图像应该有多大 .
function findSize (targetHeight, xRatio, yRatio) {
var widthCalc = Math.round((xRatio * targetHeight) / yRatio);
return { "width" : widthCalc, "height" : targetHeight };
}
var test = calcRatio(1280,720),
dimensions = findSize(400, test.x, test.y);
//400 is what we want the new height of the image to be
2 回答
是的,如果源图像已经足够宽,则可能 . 如果它不够宽,则没有足够的数据进行裁剪,如果要保持纵横比,则需要在裁剪前缩放图像 .
这样的事情应该让你开始:
要正确保持宽高比,您应该使用GCD:
你应该做这样的事情:
这将获得一些对象的比例 . 您可以使用此信息来确定生成的图像应该有多大 .
这些是你的尺寸 . 如果您的图像周围没有任何额外的“空间”需要考虑,那么您的工作就完成了 . 否则你需要处理几个案例 .