如何修改此调整大小脚本以填充/裁剪到容器?

时间:2011-08-30 02:03:39

标签: actionscript-3 flash-cs5

我有一个简单的脚本可以调整加载图像的大小以适应特定的宽度和高度,但是我希望选项能够填充,即中心和裁剪到特定的宽度/高度 - 任何有关我如何能够的想法修改这个?

当前脚本:

function resizeImg(mc:MovieClip, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true):void{
    maxH = maxH == 0 ? maxW : maxH;
    mc.width = maxW;
    mc.height = maxH;
    if (constrainProportions) {
        mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY;
    }
}

我尝试从Soulwire中搜索DisplayUtils AS3类的代码(http://blog.soulwire.co.uk/flash/actionscript-3/fit-a-displayobject-into-a-rectangle)非常谦虚,没有评论,所以即时奋斗:(

1 个答案:

答案 0 :(得分:2)

要执行此操作,您首先需要存储原始宽度和高度,以便您可以使用它来缩放图像。除此之外,您还需要屏蔽图像并使用maxW和maxH值作为尺寸。之后,您将能够使用这样的函数:

function resizeImg(mc:Sprite, maxW:Number, maxH:Number = 0, constrainProportions:Boolean = true) : void
{
    maxH = maxH == 0 ? maxW : maxH;

    if(constrainProportions)
    {

        // First of we'll make the mc fit within the viewport

        // calulate the difference between the max and stored dimensions
        var dX:Number = maxW - originalWidth;
        var dY:Number = maxH - originalHeight;

        // evaluate values
        if (dY > dX)
        {

            // mc is wider then maxW
            // set width to max and scaleY to offset of width
            mc.width = maxW;
            mc.scaleY = mc.scaleX;
        }
        else
        {
            // mc is heigher then maxH
            // set height to max and scaleX to offset of height 
            mc.height = maxH;
            mc.scaleX = mc.scaleY;
        }

        // the mc now fits within the max viewport
        // now we'll use the same trick to fill the resized mc in the max viewport

        var dXcorrection:Number = maxW - mc.width;
        var dYcorrection:Number = maxH - mc.height;

        if (dYcorrection < dXcorrection)
        {
            mc.width = maxW;
            mc.scaleY = mc.scaleX;
        }
        else
        {
            mc.height = maxH;
            mc.scaleX = mc.scaleY;
        }


        // finally we'll center the resized mc within the max viewport 
        mc.x = (maxW - mc.width)/2;
        mc.y = (maxH - mc.height)/2;
    }
}