AS3 Access Stage Dimensions in Sub Class
Posted on | April 24, 2012 | No Comments
This post will show how to access the width and height dimensions of the stage in the preloader class.
First of all, to set the dimensions of the stage, in our main.as file, add:
[as3]
[SWF(width=’800′,height=’600′,backgroundColor=’#ffffff’,frameRate=’25’)]
[/as3]
If you are using Flash then access the stage properties panel and change the dimensions there.
Now we know what the stage dimensions are, we need to access them. Unless you are aware of the correct stage properties your instinct may be to use stage.width and stage.height, however this will only give the width and height of the current object, not the stage object.
The Solution
What you want to use are stage.stageWidth and stage.stageHeight.
In our subclass:
[as3]
//see if we have access to the stage yet. If not, wait till we do.
public function Preloader():void {
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
//add event listeners, instantiate properties, etc
private function init():void {
//… instantiate textfield with our loading message in it
//… add progress event listener
addChild(myTextfield);
myTextfield.x = (stage.stageWidth / 2) – (this.width / 2);
myTextfield.y = (stage.stageHeight / 2) – (this.height / 2);
}
[/as3]
Download the as3 preloader class.
Conclusions
We can access the width and height of the stage by using the stage.stageWidth and stage.stageHeight properties.
Posted By:Richard Parnaby-King