I'm searching for:
   
   

Richard
"No alarms and no surprises please"

My Blog



Scale and Center a Movie Clip in Flash
May 31, 2007

It's been a long time since I worked with Flash (i.e. Actionscript), probably too long.  In the past couple weeks, I have spent a substantial amount of time relearning the platform.  I've forgotten how fun it can be and since it's been about 2 releases since I spent any real time using it, it's come a long way.

I use to be quite comfortable working with Flash a few years ago but a lot has slipped my mind since then.  The fundamentals have been coming back quickly but I've been saying, "How did I do that before?"  One issue that had me stumped for a bit was being able to scale and center a dynamically loaded movie clip.

I started out manipulating the _xscale and _yscale of the movie, but didn't get the exact results that I wanted.  I'm sure it's possible to make it work, but I decided to take a different route of adjusting the _width and _height properties to fit. 

So here's what I did and it gives me the results i was looking for.

//set the maximum dimensions that you want the clip to live in
var imgMaxWidth:Number = 300;
var imgMaxHeight:Number = 240;

//the object referenced as "which" is the dynamically loaded clip
//this could be accessed in the .onLoadInit function of a MovieClipLoader listener

 //make sure the image is not too wide
 if(which._width > imgMaxWidth) {
  //calculate the height to proportion of scaled width
  var iHeight:Number = (imgMaxWidth * which._height/which._width)
  //set movie to new width and height
  which._width = imgMaxWidth;
  which._height = iHeight;
 }

 //make sure the image is not too high to fit
 if(which._height > imgMaxHeight)
 {
  //calculate the width to proportion of scaled width
  var iWidth:Number = (imgMaxHeight * which._width/which._height);
  //set movie to new width and height
  which._height = imgMaxHeight;
  which._width = iWidth;
 }

//center the clip within the bounds of the container

which._x = (imgMaxWidth/2) - (which._width/2);
which._y = (imgMaxHeight/2) - (which._height/2);

I think using the _xscale and _yscale would probably get the amount of code down a bit so I'll probably circle back and give it another go and turn it into a prototype for easier use.  

Views: 14

Comments

Note to self:

I should really wrap the calculations with a Math.floor() call.