Preloading in Flash CS3… reloaded. November 28, 2007 at 10:38 am

A major obstacle in my daily workflow with Actionscript3 is preloading the output. Like I mentioned in a previous post it´s not as trivial as it used to be in earlier Flash-Versions. I focused that mess again and came to a good solution at the end - so let´s take a look at ( you also can download the source wich contains an example):


package fr.utils {

import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.text.TextField;
import flash.utils.getDefinitionByName;

public class preloader extends Sprite {

private var canvas :*;
private var rootNode :Sprite;
private var loaderBar :Sprite;
private var callBack :Function;

private var w :int;
private var h :int;
private var rectWidth :int;
private var rectHeight :int;

private var percent :Number;

private var txt :TextField;

public function preloader() {}

public function launch( canvas:*, rectWidth:int, rectHeight:int, loaderTxt:TextField, callBack:Function ) {

this.canvas = canvas;
this.rootNode = new Sprite();
this.loaderBar = new Sprite();
this.txt = loaderTxt;
this.callBack = callBack;

this.rectWidth = rectWidth;
this.rectHeight = rectHeight;

addChild( this.rootNode );
addChild( this.txt );

this.canvas.stage.align = "TOP_LEFT";
this.canvas.stage.scaleMode = StageScaleMode.NO_SCALE;

this.w = this.canvas.stage.stageWidth;
this.h = this.canvas.stage.stageHeight;

var xPos :Number = Math.round( ( this.w / 2 ) - ( this.rectWidth / 2 ) );
var yPos :Number = Math.round( ( this.h / 2 ) - ( this.rectHeight / 2 ) );

this.rootNode.x = xPos;
this.rootNode.y = yPos

this.rootNode.graphics.lineStyle( 1, 0xFFFFFF );
this.rootNode.graphics.drawRect( 0, 0, this.rectWidth, this.rectHeight );

this.rootNode.addChild( this.loaderBar );

this.rootNode.addEventListener( Event.ENTER_FRAME, catchBytes );

}

private function catchBytes( event: Event):void {

this.percent = Math.round( ( this.canvas.loaderInfo.bytesLoaded / this.canvas.loaderInfo.bytesTotal ) * 100 );

this.loaderBar.graphics.beginFill( 0xFFFFFF );
this.loaderBar.graphics.drawRect( this.loaderBar.x - this.loaderBar.x, this.loaderBar.y - this.loaderBar.y, this.rectWidth, ( this.rectHeight * this.percent ) / 100 );

this.txt.text = this.percent + "%";

if ( this.canvas.loaderInfo.bytesLoaded >= this.canvas.loaderInfo.bytesTotal ) {

removeChild( this.txt );
removeChild( this.rootNode );
this.rootNode.removeEventListener( Event.ENTER_FRAME, catchBytes );

this.callBack();

}

}

}

}


That´s my way of preloading AS3-contents for the future. The class could be a little more handy anyway, but for the fact it´s as little as version0.1, let´s see what next
enhacements version0.2 may bring.

Leave a Reply