我有一个尺寸容器:
container.width,container.height
我有一张尺寸图片:
picture.width,picture.height
我的目标是计算最佳比例,使图片适合容器(不变形)
whay会是获得比率的算法吗?
picture.width*=ratio;
picture.height*=ratio;
(图片已经集中在容器中)
答案 0 :(得分:6)
按如下方式计算缩放比例。
var ratio:Number = Math.min(
container.width / picture.width,
container.height / picture.height);
然后将缩放比例均匀地应用于图片以使其适合容器。
picture.scaleX = picture.scaleY = ratio;
答案 1 :(得分:2)
只有两种可能性:要么将图片的宽度调整到容器的宽度,要么将图片的高度调整到容器的高度。试试两个。对于每个,计算缩放适合容器的尺寸(宽度或高度)所需的比率,并使用它来缩放图片的其他尺寸:如果这导致图片尺寸超过相应的容器尺寸,那么这种可能性是行不通的。
除非图片的宽高比等于容器的宽高比,否则这两种可能性中的一种是可行的,在这种情况下它们都会(但那时它们将相同)。 / p>
答案 2 :(得分:1)
你可以这样做:
picture.width = container.width;
picture.scaleY = picture.scaleX;
if(picture.height > container.height)
{
picture.height= container.height;
picture.scaleX = picture.scaleY;
}
答案 3 :(得分:0)
您可以使用该功能返回图片的比例:
function scaleRatio(cw:Number, ch:Number, pw:Number, ph:Number):Number
{
return (ch / cw > ph / pw) ? cw / pw : ch / ph;
}
picture.scaleX = picture.scaleY = scaleRatio(container.width, container.height, picture.width, picture.height);
答案 4 :(得分:0)
好吧如果你不介意边框(例如:方形容器中的宽/风景图片的黑色边框等)
公式为:原始宽度/原始高度*新宽度=宽高比正确新高度
在你的情况下,这将是:
image.height = (image.width / image.height) * container.width;
替代版本:
image.width = container.width;
image.height = container.width / (image.width / image.height);