# 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,

1. OnfireDesigns
Posted January 20, 2009 at 6:43 pm | Permalink

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!!!!!!!!

2. Posted January 28, 2009 at 6:16 pm | Permalink

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?

• Posted January 29, 2009 at 10:48 am | Permalink

@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?

3. Posted January 29, 2009 at 3:54 pm | Permalink

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.

• Posted January 30, 2009 at 11:58 am | Permalink

@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…

4. Posted January 30, 2009 at 7:35 pm | Permalink

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.

• Posted January 30, 2009 at 11:46 pm | Permalink

@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.

5. Posted January 31, 2009 at 2:23 pm | Permalink

“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!

6. Posted February 2, 2009 at 4:37 pm | Permalink

@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!

7. Emrah
Posted March 5, 2009 at 5:22 am | Permalink

Very very thanks.

8. Matt
Posted March 23, 2009 at 6:23 pm | Permalink

Thank you so much for this!!

9. lululemon
Posted April 22, 2009 at 7:30 pm | Permalink

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?

10. Posted April 24, 2009 at 9:45 am | Permalink

@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?

11. Posted May 15, 2009 at 1:47 am | Permalink

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

• Posted May 15, 2009 at 10:08 am | Permalink

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

12. Inderdeep
Posted May 27, 2009 at 9:12 am | Permalink

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

Thank you again…
Regards
Inderdeep

13. Visualosopher
Posted May 27, 2009 at 11:31 pm | Permalink

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-

• Posted May 30, 2009 at 7:48 am | Permalink

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);

14. Visualosopher
Posted May 31, 2009 at 11:29 pm | Permalink

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

15. circlecube
Posted July 8, 2009 at 12:41 pm | Permalink

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;     } }
16. binteali
Posted August 1, 2009 at 2:47 pm | Permalink

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.

17. binteali
Posted August 1, 2009 at 5:11 pm | Permalink

Quick update…I figured it out and fixed it.

bA.

18. Posted September 15, 2009 at 10:19 am | Permalink

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!

• Posted December 30, 2009 at 10:21 am | Permalink

@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!

19. Kara Vojak
Posted December 8, 2009 at 1:53 am | Permalink

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

20. Posted December 28, 2009 at 6:17 pm | Permalink

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

• Posted December 30, 2009 at 10:21 am | Permalink

@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.

21. Posted January 19, 2010 at 8:45 pm | Permalink

Thank You! Beautiful peace of code.

22. Zen
Posted February 16, 2010 at 8:22 am | Permalink

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;

• Posted February 16, 2010 at 9:43 am | Permalink

@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
Posted February 16, 2010 at 11:06 am | Permalink

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!

23. StuJ
Posted March 12, 2010 at 5:09 pm | Permalink

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.

24. emme
Posted March 20, 2010 at 7:22 am | Permalink

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.

25. Luis l
Posted June 9, 2010 at 10:55 pm | Permalink

Thank you Thank you Thank you!!!

26. Posted June 29, 2010 at 5:41 am | Permalink

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

27. Zik
Posted August 9, 2010 at 12:34 am | Permalink

The world needs more people like you.

Thank you very very very much.

28. Posted September 1, 2010 at 8:33 pm | Permalink

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]

• Posted September 3, 2010 at 1:23 pm | Permalink

@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.

29. Valdemar
Posted October 5, 2010 at 6:12 am | Permalink

Thank you. It was useful!

30. asao
Posted October 9, 2010 at 1:11 pm | Permalink

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

31. jerry
Posted January 30, 2011 at 3:46 am | Permalink

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

32. Kash
Posted April 25, 2011 at 1:43 pm | Permalink

Excellent code, works flawlessly!!!

33. Erik E
Posted May 5, 2011 at 6:03 pm | Permalink

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!

34. billy
Posted September 19, 2011 at 11:36 am | Permalink

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

35. me-gamer
Posted February 9, 2012 at 3:43 am | Permalink

36. Saravanan
Posted May 29, 2012 at 6:15 am | Permalink

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.

37. Posted June 3, 2012 at 10:44 am | Permalink

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

38. Hendra
Posted July 11, 2012 at 8:29 am | Permalink

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?

Subscribe without commenting

## Presenting at WordCamp Atlanta – Child Themes

The presentation? Your firstborn child theme. Child themes 101+2. I’m speaking at wordcamp atlanta this afternoon about themes and child themes. I’ll update this post with post-presentation notes. Learn how to mod themes the right way. Using child themes you won’t loose your edits when there’s a theme update. (101) We’ll go over the advantages [...]

## Hooks, In a Nutshell – WP Daily

I’ve published another article over on wpdaily.co exploring the concept of hooks. I remember when starting out that people kept mentioning hooks and filters and actions and… it took a while to grasp what they each meant. I think the first time I started to grasp it was when I read the codex and saw [...]

## Speaker at WordCamp Atlanta 2013

I’m excited to be speaking at WordCamp Atlanta again this year! The time is quickly approaching for WordCamp Atlanta 2013, March 15-16. I spoke last year and discussed the process of going from Photoshop PSD to WordPress Theme, here are my slides and notes for that WordCamp Presentation. This year I’m speaking along the same [...]

## WP Features: Theme or Plugin

Reading my wpdaily.co updates today and saw this post talking about WordPress theme features. Eric explains the debate: Generally-speaking, the conversations have always circled around features: There are those that believe every feature you could ever imagine should be included like text color, font selector, and more. On the flip-side, there are those that feel [...]

## Packery Preview, from Metafizzy & descended from Masonry

David Desandro / metafizzy, maker of masonry and isotope of which I’m a big fan and user of has been busy with a new project called Packery. Packery, looks to be a child of Masonry. As you would expect it seems to be pushing things much further and addressing a few pain points of masonry. [...]

## On Going Responsive (responding to Where to Start)

I needed to write this up about going responsive in response after reading Where to Start (by Trent Walton of Paravel) about getting started with responsive web design. Thanks for sharing your thoughts Trent, I agree whole heartedly. In my experience it is the same. I wanted to share his post and also add my [...]

### Evan Mullins

The keystore is used for creating valid apps that are associated with the author. It is not...

### Rohan Dave

I am new in android and have certain question about KeyStore. Is KeyStore used in user...

### arpit

very useful thank you …..

### Duan

@ugh You’re joking, right? I do some basics in Flash, but come on – all you do is...

### Cátia Vala

Thank you so much Evan! That’s great! Keep going with your amazing work.

### zproxy

thanks i bet its faster to google and find some ad hoc documentation than the other way.