Wednesday, November 12, 2008

Measuring the Stage in AS3

In AS2 you could measure the stage using Stage.width. in AS3 things are different.

In AS3 stage.width works BUT it gives you the measurement of all the items in the stage - not the width of the player window.

This person has an interesting workaround. Basically you create an empty movieclip, convert it to a Stage, then measure it. Because there is nothing in it, it measures what it can, so measures the player window!

At least that is how I understand it. Here is the code:

var myMC:MovieClip = new MovieClip();
addChild(myMC);
var _stage:Stage = myMC.stage;


Then you use this to get the measurement:

_stage.stageWidth


This even works in SWFs that are loaded in a parent shell SWF.

4 comments:

eLouai said...

It's much simpler to use

trace(stage.stageWidth);
trace(stage.stageHeight);

This would give you the ACTUAL viewport of the stage.

stage.width
stage.height
Gives you the width of the display object with all the objects added to it.

Anonymous said...

Actually, you're not converting your new MovieClip into a Stage. There is only one Stage, just like when you're using AS2. The diffrerence is that in AS3 the Stage can only be referenced as a property of a DisplayObject when that DisplayObject is on the display list. So by creating an empty MovieClip and adding it to the display list, you can get a reference to the Stage.

TypicalFashion said...

so strange... like eLouai said, why not just use stageWidth instead of doing all that just to look for width of a stage object heh...

Matt Maxwell said...

It's been a while since the post, but I seem to remember that my bizarre code was necessary because I was using percentages rather than fixed dimensions in the browser embed and the normal stuff wasn't giving me the actual dimensions of the full-browser window flash. If I remember right, this code gives the dimensions of the actual browser window (not just the Flash stage) when the embed dimesions are set to 100%x100% I wish I could remember exactly what it was. I promise there was a good reason behind my madness. I'm remembering more now. The commands you specified wre returning the width of the contents on the stage and they would keep changing depending on the size of the display objects. My code gave an unchanging measurement of the browserwindow that was independant of the display objects' widths. But thanks for the feedback.