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


February 11th, 2007 at 10:53 pm
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);
February 12th, 2007 at 12:36 am
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
February 21st, 2007 at 2:54 pm
Do you have a link to where this is being used as an example? Thanks.
March 6th, 2007 at 11:51 am
Is there a way to make this work if your stage align is centered…as opposed to top left?
March 6th, 2007 at 10:15 pm
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.
March 6th, 2007 at 10:15 pm
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.
March 7th, 2007 at 8:03 am
worked like a charm…thanks John!