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

// this tells Flash NOT to allow the assets to be scaled
Stage.scaleMode = "noScale";
Stage.align = "TL";

// need to set up a listener object to say when the stage is resized.
var stageListener:Object = new Object();
Stage.addListener(stageListener);

setBackground();

// called when the stage is resized
stageListener.onResize = function() {
setBackground();
}

function setBackground() {

// determine middle
var middleX = Stage.width/2;
var middleY = Stage.height/2;

// reposition the bkgd to middle
bkgdMC._x = middleX;
bkgdMC._y = middleY;

// scale background to fit width and height
bkgdMC._width = Stage.width;
bkgdMC._height = Stage.height;

// see if it grew bigger horizontally or vertically and adjust other to match
// to maintain aspect ratio
bkgdMC._xscale  >  bkgdMC._yscale ? bkgdMC._yscale = bkgdMC._xscale : bkgdMC._xscale = bkgdMC._yscale;

}