# How to as3 resize a movieClip and constrain proportions | Actionscript Tutorial

I’ve had that exact task numerous time while scripting actionscript. I have a source image loaded externally or a mc within the program and I need to fit it into a certain area (width x height) but keep the aspect ratio the same or as photoshop calls it “constrain proportions”. I’ve done this with fancy and not so fancy formulas and equations, but finally I had it and created a simple function that would do it every time. Figured it was worth sharing cause if I’ve googled it before then others most likely will too!

This is more than just setting the width and height of an object, because that way the image is easily skewed and the natural proportions are messed up. If you want to just use scale you need to know the dimensions of the image being resized, and that’s just not scalable (no pun intended).

What we have to do is to do both. Assign the width and height to skew it, and then scale it to correct the proportion. So if we want to resize an image when we don’t know it’s current size to fit into a 300 pixel square we set the width and height of that image to 300 and then a bit of logic that can be summed up in one line:

 1 mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY;

That says if the x scale is larger than the y scale set the x to the y scale amount, and vice versa. It’s basically setting both scales to the smaller of the two. This works because we don’t know the original size of the image, but actionscript does. scaleX and scaleY are ratios of the current width and height to the originals. A little complicated I know, but that’s why I’ve made the function below. I know how to use it and now I don’t have to think about skewing and then scaling back to keep my aspect ratio or proportion. You should see how to use it just by looking at it:

 1 resizeMe(mc:MovieClip, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true)

Pass in the movieClip you want to resize, and the size you want it to fit into. So with the same example above, just do

 1 resizeMe(image, 300);

## Example

Here’s an interactive example to show what I mean. It loads an external image and you click and drag the mouse around to resize it. To toggle whether you want to constrain proportions use the space bar. Type a url to any image you want to test it with and press load, or hit ‘enter’.

Here’s a screenshot of me playing with a photo in here NOT constraining proportions.

## Source (AS3)

The resizing function

 1234567891011121314 //The resizing function // parameters // required: mc = the movieClip to resize // required: maxW = either the size of the box to resize to, or just the maximum desired width // optional: maxH = if desired resize area is not a square, the maximum desired height. default is to match to maxW (so if you want to resize to 200x200, just send 200 once) // optional: constrainProportions = boolean to determine if you want to constrain proportions or skew image. default true. function resizeMe(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;     } }

The full source

constrainProportions.fla

And as usual, let me know if you’ve got any comments questions or suggestions! Thanks,

• OnfireDesigns

Great job!!! I love it when people like you make my life easier! Just what i needed as i was working on a flash site with video player and was just going to input the static dimensions to resize my video.

Thanks Alot!!!!!!!!

• http://www.reallyhq.com Devin Columbus

Hey Evan,

Great code, first of all… I have a question though… How would you keep an image it’s original size until it gets to be the maxW or maxH? In other words, dont stretch the image, only constrain it?

• http://circlecube.com Evan Mullins

@Devin – Thanks, I’m glad it helped. If I understand your question: You want to only scale an image until it gets to a certain size? This function should do that, you pass in the maxW and maxH and a boolean to determine if you want to constrain proportions or skew image. Passing in a true boolean, or nothing- since the default is true, it will constrain proportions.
Did I understand you correctly?

• http://www.reallyhq.com Devin Columbus

Close, but opposite… let’s say I have an area of 320×240 and I have two images… one is 100×100 and the other is 400×325. Given the area that I have to work with, I don’t want to change the size of the 100×100, because it will stretch. But I do want to scale down the 400×325 image. See what I’m saying? So only if any image is either too wide or high or both do I want to reduce it’s size.

• http://circlecube.com Evan Mullins

@Devin – this function would still work. You would call it like this:

 1 resizeMe(image_400Ã—325, 320, 240);

That will scale down the larger image and fit it into the desired area. With a couple tweaks you can even center the image in that area…

• http://www.reallyhq.com Devin Columbus

Yeah, that part of the function works… but check it out if an image is smaller than the maxH and maxW … the image stretches to fit the area. That’s what I want to prevent… essentially not do anything unless the image is too big.

• http://circlecube.com Evan Mullins

@Devin – Now I see; I assumed you weren’t passing images to the function that you didn’t want resized… but if this is scripted you won’t know really, so the function should be able to determine if the image needs resizing or not.
I’d recommend putting this into an if statement and only apply the resizeMe function if the image is ‘out of bounds’.

 123456 if (image.width > maxW || image.height > maxH) {    resizeMe(image, maxW, maxH); } else{    //don't resize me }

or if you really wanted to you could add that into the function. When I designed the method, I was picturing instances where I would always want the image to be a certain size. I understand in your situation you probably don’t want to pixelate the 100×100 when you scale it 2.4 times. It’d be pretty simple to modify the resizeMe function to only shrink images to fit within a certain area, and it’d be pretty simple too to add a bit that would center the image in the specified area. Let me know what you decide is best for your scenario.

• http://www.reallyhq.com Devin Columbus

“It’d be pretty simple to modify the resizeMe function to only shrink images to fit within a certain area, and it’d be pretty simple too to add a bit that would center the image in the specified area.”

Both of those things sound absolutely perfect. I’m loading the image into a imageHolder MovieClip right now. Perhaps you could help me out with the function modifications? I really do appreciate it!

• http://circlecube.com Evan Mullins

@Devin – ok I’ll give it a quick shot:

 123456789101112131415 function resizeMe(mc:MovieClip, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true):void{     //if only one param is sent in, make the max area square     maxH = maxH == 0 ? maxW : maxH;     //check to see if image is bigger than max area, resize     if (mc.width > maxW || mc.height > maxH){         mc.width = maxW;         mc.height = maxH;         if (constrainProportions) {             mc.scaleX < mc.scaleY ? mc.scaleY = mc.scaleX : mc.scaleX = mc.scaleY;         }     }     //center the image in the area     mc.x = maxW/2 - mc.width/2;     mc.y = maxH/2 - mc.height/2; }

That should give you something to start with at least, may have to mess with the centering if the max area isn’t at 0,0.
Let us know what you come up with!
Good luck!

• Emrah

Very very thanks.

• Matt

Thank you so much for this!!

• lululemon

thanks for this. However, I need to load both external swf, and also .flv or f4v files. Thus I created a video within a movieclip. create teh NewConnection, and NetStream. On the MetaData, I will set the size and the x and y cooridinates. However, in my metaData function, I try to do the following to my video,
mv.scaleX < mv.scaleY ? mv.scaleY = mv.scaleX : mv.scaleX = mv.scaleY;

It doesn’t seem to work. It still just takes whatever I set in the width and height. Any idea why? How do I constraint the proportion for Video?

• http://circlecube.com Evan Mullins

@lululemon,
That line of code looks like it should work. I’ve used it for some video players myself, as long as you’re applying it in the right place. If the video hasn’t actually loaded yet, then the script won’t really do anything, maybe try to apply the effect after a short delay?

• http://www.mediavan.be Geoff

Hi Evan, this helped me out really quick! Thanks for that!

Just one small thing.
I needed to resize a Bitmap, so “private function resizeMe(mc : Movieclip,…” didn’t work of course. So to make it a bit more flexible, you can easily change this to “private function resizeMe(mc : DisplayObject”.

Thanks again!
geoff

• http://circlecube.com Evan Mullins

@Geoff – Sure thing, Thanks for pointing that out!

• Inderdeep

Thanks for this nice tip to resize the Image with Proportions … It saved my lot of time..

Thank you again…
Regards
Inderdeep

• Visualosopher

Hi Evan –

Thanks for this awesome tutorial.

I am trying to load various sizes of images from XML to resize to a maximum height of 250 px once in Flash for a slideshow that scrolls.

In your great code you have this:

// optional: maxH = if desired resize area is not a square, the maximum desired height. default is to match to maxW (so if you want to resize to 200×200, just send 200 once)
// optional: constrainProportions = boolean to determine if you want to constrain proportions or skew image. default true.

What do you mean by “just send the 200 once”?

I also replaced MovieClip below in your code with DisplayObject, thinking it is a start from the the above thread. My source files are also external and the FLA runs from a main.as class if that helps.

Any ideas about how your function below may be able to work?

function resizeMe(mc:DisplayObject, 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;
}
}

Any pointers are greatly appreciated since I have been trying for two days and I am a newbie to AS3.

Thanks-

• http://circlecube.com Evan Mullins

What do you mean by “just send the 200 once”?

I mean if your desired size is a 200×200 square, you can just call the function like so: resizeMe(image, 200);
but if you want it 200×300 do it like so: resizeMe(image, 200, 300);

If I understand you correctly, include this function in your code and then once your image has loaded (maybe on the onComplete event handler) call resizeMe(myDisplayObject, 250);. This will resize the image to a 250px square. Ah, I think I understand your question now. You want to set all images to 250px height and have a variable width? Good question I hadn’t thought of this use case before. So you don’t care what the width is, but you need the height to be certain, and if you only send in the height this method assumes you want a square… I’d first try commenting out the second line (mc.width = maxW;), if you are lucky then that will do it. It won’t set the width from the received param anymore and only once height is 250px width should be set by proportion. resizeMe (image, 250);

I’m thinking it would be pretty simple to update the function so you could send in a boolean “false” for either width or height to specify that you don’t care about that dimension, and it will soley focus on the other one. Then you could potentially use the method in multiple ways without loosing functionality. resizeMe(image, false, 250);

• Visualosopher

Thanks, you rock –
I’ll give it a shot and let you know if it worked-

• circlecube

I've got a couple updates to this function to center the image in the max area:

 12345678910111213141516171819202122 //The resizing function // parameters // required: mc = the movieClip to resize // required: maxW = either the size of the box to resize to, or just the maximum desired width // optional: maxH = if desired resize area is not a square, the maximum desired height. default is to match to maxW (so if you want to resize to 200x200, just send 200 once, ie resizeMe(image, 200);) // optional: constrainProportions = boolean to determine if you want to constrain proportions or skew image. default true. // optional: centerHor = centers the displayObject in the maxW area. default true. // optional: centerVert = centers the displayObject in the maxH area. defualt true. function resizeMe(mc:DisplayObject, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true, centerHor:Boolean=true, centerVert: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;     }     if (centerHor) {         mc.x = (maxW - mc.width) / 2;     }     if (centerVert){         mc.y = (maxH - mc.height) / 2;     } }
• http://www.circlecube.com/ Evan Mullins

I’ve got a couple updates to this function to center the image in the max area:

//The resizing function
// parameters
// required: mc = the movieClip to resize
// required: maxW = either the size of the box to resize to, or just the maximum desired width
// optional: maxH = if desired resize area is not a square, the maximum desired height. default is to match to maxW (so if you want to resize to 200×200, just send 200 once, ie resizeMe(image, 200);)
// optional: constrainProportions = boolean to determine if you want to constrain proportions or skew image. default true.
// optional: centerHor = centers the displayObject in the maxW area. default true.
// optional: centerVert = centers the displayObject in the maxH area. defualt true.
function resizeMe(mc:DisplayObject, maxW:Number, maxH:Number=0, constrainProportions:Boolean=true, centerHor:Boolean=true, centerVert: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;
}
if (centerHor) {
mc.x = (maxW – mc.width) / 2;
}
if (centerVert){
mc.y = (maxH – mc.height) / 2;
}
}

• binteali

Hey,

Thanks a lot for sharing this! It's just what I've been hunting for, but being a complete newbie to AS3, I've stumbled across what I think (hope!) might be problem with a very simple solution. (Only I can't figure it out!)

I've used your code to place an external swf on my stage, but within a movieclip. When you click a button, the play head is supposed to move to the specific frame that has that movieclip and then play the swf.

The code shows no errors, but when I try to compile I get a
“Error 1046: Type was not found or was not a compile-time constant” with reference to the name of the movieclip.

I've found plenty of forums with the similar problems but none of the solutions is clear enough for newbie like me to understand Any help would be much much appreciated…
bA.

• binteali

Hey,

Thanks a lot for sharing this! It’s just what I’ve been hunting for, but being a complete newbie to AS3, I’ve stumbled across what I think (hope!) might be problem with a very simple solution. (Only I can’t figure it out!)

I’ve used your code to place an external swf on my stage, but within a movieclip. When you click a button, the play head is supposed to move to the specific frame that has that movieclip and then play the swf.

The code shows no errors, but when I try to compile I get a
“Error 1046: Type was not found or was not a compile-time constant” with reference to the name of the movieclip.

I’ve found plenty of forums with the similar problems but none of the solutions is clear enough for newbie like me to understand Any help would be much much appreciated…
bA.

• binteali

Quick update…I figured it out and fixed it.

bA.

• binteali

Quick update…I figured it out and fixed it.

bA.

• http://www.podereilcasale.it Aaron

Thank you very much for this. My resize functions are maybe too complicated so they fall flat. This works perfectly and here is a version that instead of resizing, returns an Object with the values: object.w and object.h. This is for if you need to tween something and don’t want to immediately change the dimensions.

 123456789101112131415161718 function resizeMe(s:MovieClip,maxW:Number,maxH:Number = 0):Object{             maxH = maxH == 0 ? maxW : maxH;             var origW = s.width;             var origH = s.height;             var scalex = maxW/origW;             var scaley = maxH/origH;             if(scalex < scaley){                 scaley = scalex             }else{                 scalex = scaley             }             var w = scalex*origW;             var h = scaley*origH;             var  object:Object = new Object();             object.w = w;             object.h = h;             return object;         }

and to use it…

 123 var tempObj:Object = resizeMe(myMC,200); tweenToWidth:Number = tempObj.w; tweenToHeight:Number = tempObj.h;

Hope this helps someone. And thanks again for the great code!

• http://circlecube.com Evan Mullins

@Aaron – This is a great idea! I hadn’t thought to do it like this but a great way to enable tweening easily. Thanks for sharing!

• Kara Vojak

I NEED MAJOR HELP!

I am making a website in dreamweaver using adobe cs4 series. I am inserting .swf files into my dreamweaver template. I am using a liquid dreamweaver template with a heading, footer, body, and a sidebar on each side of the body, ect.

My problem is…. when i insert the .swf file, everything works great when i preview it except i cant seem to get the .swf file to stretch when i change browser sizes so that it fits the length of the header. Im NEW to flash and trying to figure this out on my own. IV BEEN SEARCHING GOOGLE FOR THE ANSWER FOR 3 HOURS NOW AND GETTING FRUSTRATED! PLEASE HELP!

I basically need to make the .swf filel liquid to my header so it stays within the borders of the header when i change minimize or maximize my browser or change browser size. If i didnt explain this well, please message me back and let me know.

kara

• http://zee7.deviantart.com zee7

is this possible to do in actionscript 2.0, have you got any example for 2.0, please must reply me, thanks

• http://circlecube.com Evan Mullins

@zee7 – I’m sure it is possible in as2, it’s just some math to resize the display object. I haven’t done it though, shouldn’t be too difficult though -of course some things would need changing like using the old ‘_width’ rather than ‘width’ properties.

• http://www.emerge.pl Marek Mis

Thank You! Beautiful peace of code.

• Zen

Hey, thank you so much for this code, it works great, but I have a little problem..

I’m using a loop to load a few images through an xml file and I’m not sure how should I properly target the images with your function. I’ve tried to set it up like in the example, but nothing gets loaded that way. I have copied only the part of the code where I’m guessing the issue is.

I’d really appreciate any help, thanks!

{
xml = XML(e.target.data);
imageList = xml.children();
curItem = i;

for(var i:int = 0; i < imageList.length(); i++)
{
mainContainer.x = (i * (mainCWidth + 136))+ 68;
mainContainer.alpha = 0;
imageHolder.y = 7;
resizeMe(imageHolder, 550, 450);
TweenLite.to(mainContainer, 0.4, {alpha:1, delay:1.2, ease:Linear.easeOut});
}
}

function resizeMe(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;
}
}

var constrainOn:Boolean = true;

• http://circlecube.com Evan Mullins

@Zen – are your images loading but just not resizing properly? I’d do some trace statements to make sure the url to the image is properly formatted and loading an image. And it could be that your are resizing them before they actually have time to load. I’d recommend putting your call to the resizeMe function into an on load complete even handler.

• Zen

It was the former. However, they become tiny after the resizing, because the only thing I can resize is the mc that contains all of the images.. well loops probably aren’t the best way to load images anyway Its time I learn more about arrays..

Thanks for helping me out Evan!

• StuJ

took a little while to sink in it makes perfect sense now! (I’ve had a beer!) And it works! Didnt take long to get it centred as well, so thank you for posting this.

• emme

Great job! I love you haha… I was going crazy, google-ing every day looking for a solution to a as3 constrain proportions resize, without any good and solid solution.
I’m a html/css web developer and this stupid need was so easy-accomplished with Javascript: Flash was driving me mad.

Thanks again for sharing this.
Best wishes!

m,
from Italy.

• Luis l

Thank you Thank you Thank you!!!

• http://www.ratestotravel.info Jane

Great post, exactly what i was searching for, resizing now is a peace of cake thanks for sharing!

• Zik

The world needs more people like you.

Thank you very very very much.

• http://www.tellytube.tv Patrick

Need some help here~ forgive if this isn’t related. I have created a flash animation that includes a billboard that I want to load two external .swfs into. I have implemented this code:

var url:URLRequest = new URLRequest(“getpaid.swf”);

}

function on_progress(e:ProgressEvent):void {

trace(e.bytesLoaded + ” out of ” + e.bytesTotal);

}

___________

Currently, the published animation contains the .swf floating throughout the entire timeline.

I need the .swfs to come in at a specific frame, in a specific location, with a slight rotation and constrained resizing.

Can you help?

Many Thanks!

[email protected]

• http://circlecube.com Evan Mullins

@Patrick – I’d think you’d need a variable to tell it when to load (which frame number specifically) and in that load_completed function set the rotation and scale.

• Valdemar

Thank you. It was useful!

• asao

Thank you!!!! Found exactly what I needed.

• jerry

you just saved me days and days of misery. Thanks a million.

• Kash

Excellent code, works flawlessly!!!

• Erik E

Hello,

i’ve got a question. Is it possible to make a load from a local image? I will use it as a photo viewer. So i needed a button to ‘open’ my local drive. I choose the file (jpg, gif, png) and click on ok and it is opening in the swf.

So not a load from an url but from a search trough my hard drive.

Who can help me for this modification?

Thanks a lot!

• billy

Awesome job dude! You saved me hours and hours of coding! I added your blog to my favourites!
THANKS!!!!

• me-gamer

• Saravanan

Very good knowledge share. You have provided the complete info. It is very useful to me. After searching many sites, I am ended up here.

• http://www.gertjanmeire.be Gert-Jan

Thx for this! Helped me out alot for a school project!

• Hendra

Hi, can you give me sample with use button resize. i have try implement it use button but good work with when constrain = false. when it true button resize will outside of image. can you help me please?

• ### Recent Posts

There needs to be a cultural change in how we approach building for the web. Yes, some of the tools we choose are part of the problem, but the bigger problem is that performance still isn’t being recognised as the most important factor in how people feel about websites (and by extension, the web). This […]

## human_time_diff « WordPress Codex

Determines the difference between two timestamps.The difference is returned in a human readable format such as “1 hour”, “5 mins”, “2 days”. Source: Function Reference/human time diff « WordPress Codex Used this little known, but nice gem today. It’s a core WordPress function that gives human relative time from any other datetime in “U” format. […]

## Cyclomatic Complexity: Logic in CSS – CSS Wizardry – CSS, OOCSS, front-end architecture, performance and more, by Harry Roberts

I recently hit upon a way of thinking that made me realise that CSS does include logic, and the fact that it’s rarely viewed as such is probably also why we end up with such poor CSS at all.I found myself explaining compound selectors to a client as being made up of the subject—the thing […]