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

constrain proportions jpgI’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:
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:
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
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'.
[kml_flashembed fversion="9.0.0" movie="https://circlecube.com/wp-content/uploads/2009/01/constrainproportions.swf" publishmethod="dynamic" width="550" height="550"]

Get Adobe Flash player

[/kml_flashembed]

Here's a screenshot of me playing with a photo in here NOT constraining proportions.
constrain proportions jpg

Source (AS3)

The resizing function
[cc lang="actionscript"]
//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; } } [/cc] The full source [cc lang="actionscript"] var defaultUrl:String = "https://circlecube.com/wp-content/uploads/2008/11/circlecubelogo4.png"; var image:MovieClip = new MovieClip(); loadImage(); function loadImage(url:String=""):void { if (url == "" || url == defaultToLoadString) url = defaultUrl; //clear image image.visible = false; image = new MovieClip(); //add image var ldr:Loader = new Loader(); var urlReq:URLRequest = new URLRequest(url); trace("loading image: " + url); ldr.load(urlReq); ldr.contentLoaderInfo.addEventListener(Event.COMPLETE, imageCompleteHandler); image.addChild(ldr); addChild(image); } function imageCompleteHandler(e:Event):void { resizeMe(image, stage.stageWidth) } //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; } } var constrainOn:Boolean = true; var isPressed:Boolean = false; stage.addEventListener(MouseEvent.MOUSE_MOVE, moved); stage.addEventListener(MouseEvent.MOUSE_DOWN, pressed); stage.addEventListener(MouseEvent.MOUSE_UP, released); stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownListener); function keyDownListener(e:KeyboardEvent) { if (e.keyCode == 32){//spacebar toggled(e); } if(e.keyCode == 13){//enter loadImagePress(e); } } function moved(e:Event):void{ if (isPressed) resizeMe(image, mouseX, mouseY, constrainOn); } function pressed(e:MouseEvent):void{ isPressed = true; moved(e); } function released(e:MouseEvent):void{ isPressed = false; } function toggled(e:Event):void{ constrainOn = !constrainOn; moved(e); } var defaultToLoadString:String = "type url of image to load"; toLoad.text = defaultToLoadString; toLoad.addEventListener(FocusEvent.FOCUS_IN, toLoadFocus); toLoad.addEventListener(FocusEvent.FOCUS_OUT, toLoadBlur); function toLoadFocus(e:FocusEvent):void{ if (toLoad.text == defaultToLoadString) toLoad.text = ""; } function toLoadBlur(e:FocusEvent):void{ if (toLoad.text == "") toLoad.text = defaultToLoadString; } loadBtn.addEventListener(MouseEvent.CLICK, loadImagePress); function loadImagePress(e:Event):void{ loadImage(toLoad.text); } [/cc]

Download

constrainProportions.fla

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

51 thoughts on “How to as3 resize a movieClip and constrain proportions | Actionscript Tutorial

  1. 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. 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?

    1. @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. 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. :)

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

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

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


      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. “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. @Devin – ok I’ll give it a quick shot:

    [cc lang=”actionscript”]
    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; } [/cc] 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. 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?

    Thanks in advance.

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

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

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

    Thank you again…
    Regards
    Inderdeep

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

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

  12. 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 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;
    }
    }

  13. 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;
    }
    }

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

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

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

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

    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!

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

    CAN ANYONE HELP ME PLEASE?

    kara

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

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

    function loadMain():void
    {
    xml = XML(e.target.data);
    imageList = xml.children();
    curItem = i;

    for(var i:int = 0; i < imageList.length(); i++)
    {
    mainContainer = new Loader();
    mainContainer.load(new URLRequest(imageList[i].attribute("main")));
    mainContainer.x = (i * (mainCWidth + 136))+ 68;
    mainContainer.alpha = 0;
    imageHolder.y = 7;
    imageHolder.addChild(mainContainer);
    addChildAt(imageHolder, 1);
    resizeMe(imageHolder, 550, 450);
    TweenLite.to(mainContainer, 0.4, {alpha:1, delay:1.2, ease:Linear.easeOut});
    }
    }
    loadMain();

    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;

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

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

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

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

  21. 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 child_loader:Loader = new Loader();

    addChild(child_loader);

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

    child_loader.load(url);

    child_loader.contentLoaderInfo.addEventListener(Event.COMPLETE, load_completed);

    child_loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, on_progress);

    function load_completed(e:Event):void {

    child_loader.x = 50;

    child_loader.y = 50;

    }

    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]

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

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

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

  24. 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?

Comments are closed.