How can I ammend this resize script to fill/crop to container?
I've got a simple script that resizes a loaded image to fit a specific width and height, however I want the option to be able to fill i.e. centre and crop to a specific width/height - any ideas on how I can modify this?
Current script:
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;
}
}
I tried picking through the code of the DisplayUtils AS3 class from Soulwire (http://blog.soulwire.co.uk/flash/actionscript-3/fit-a-displayobject-into-a-rectangle) but its pretty well obfusticated and has no comments so im struggling :(
To do this you'll first need to store the original width and height so you can use it to scale the image. Besides that you'll need to mask the image and use your maxW and maxH values as it's dimensions. After that you'll be able to use a function like this:
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;
}
}
精彩评论