February 11th, 2007

Scale image proportionally

A buddy of mine had asked me how to make Flash scale an image to fit the entire background, but keeping the image aspect ratio. I knew it wouldn't be hard to figure out, but I also hadn't really done it before. I'm posting it here for his benefit and just in case I need to look back sometime in the future. I make no promises that this is the most efficient way either, but it definitely works. The real "trick" is scaling the background image movieclip to the width and height of the Stage and then checking to see which scale (xscale or yscale) is bigger and scaling the other to match.

Here is the code and the FLA (LINK):

Actionscript:

  1. // this tells Flash NOT to allow the assets to be scaled
  2. Stage.scaleMode = "noScale";
  3. Stage.align = "TL";
  4.  
  5. // need to set up a listener object to say when the stage is resized.
  6. var stageListener:Object = new Object();
  7. Stage.addListener(stageListener);
  8.  
  9. setBackground();
  10.  
  11. // called when the stage is resized
  12. stageListener.onResize = function() {
  13. setBackground();
  14. }
  15.  
  16. function setBackground() {
  17.  
  18. // determine middle
  19. var middleX = Stage.width/2;
  20. var middleY = Stage.height/2;
  21.  
  22. // reposition the bkgd to middle
  23. bkgdMC._x = middleX;
  24. bkgdMC._y = middleY;
  25.  
  26. // scale background to fit width and height
  27. bkgdMC._width = Stage.width;
  28. bkgdMC._height = Stage.height;
  29.  
  30. // see if it grew bigger horizontally or vertically and adjust other to match
  31. // to maintain aspect ratio
  32. bkgdMC._xscale >  bkgdMC._yscale ? bkgdMC._yscale = bkgdMC._xscale : bkgdMC._xscale = bkgdMC._yscale;
  33.  
  34. }

7 Responses to “Scale image proportionally”

  • Hi, John.
    I used the same trick for my own works.
    I don’t know whether the following code is more efficient or not. But it shorten your code, though.

    bkgdMC._xscale = bkgdMC._yscale = Math.max(bkgdMC._xscale, bkgdMC._yscale);

  • Yeah. mine code was a bit verbose because I was making it easier for my buddy to read, however, I didn’t think of using Math.max

  • Do you have a link to where this is being used as an example? Thanks.

  • Is there a way to make this work if your stage align is centered…as opposed to top left?

  • dyl - if your Stage.align was set to “T” (top center), you could comment out the line bkgdMC._x = middleX; and it should work just fine.

  • Jonathan - there is a link above to a sample FLA that you can look at. I’m sure a little looking around on the web can dig up a “live” example. Its quite common.

  • worked like a charm…thanks John!