AS2 → AS3: Loading External Assets
The MovieClipLoader is no longer available in AS3 and has been replaced by the new, hip kid on the block, the Loader class. Just like pretty much everything else in AS3, Loader has a bunch of events it fires off which you can listen to and react accordingly. Below is the AS2 code for loading an image:
-
var mcLoader:MovieClipLoader = new MovieClipLoader();
-
var loadListener:Object = new Object();
-
var mc:MovieClip = this.createEmptyMovieClip("mc", this.getNextHighestDepth());
-
-
loadListener.onLoadInit = function($target:MovieClip):Void
-
{
-
trace("IMG WIDTH: " + $target._width + "\nIMG HEIGHT: " + $target._height);
-
};
-
-
loadListener.onLoadProgress = function($target:MovieClip, $bl:Number, $bt:Number):Void
-
{
-
trace("PERCENT LOADED: " + Math.floor(($bl / $bt) * 100));
-
};
-
-
mcLoader.addListener(loadListener);
-
mcLoader.loadClip("piggie.jpg", mc);
And here is the new AS3 syntax:
-
var imgLoader:Loader = new Loader();
-
var imgRequest:URLRequest = new URLRequest("piggie.jpg");
-
imgLoader.load(imgRequest);
-
-
imgLoader.contentLoaderInfo.addEventListener(Event.INIT, showPiggie);
-
imgLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, tracePercentLoaded);
-
-
function showPiggie($evt:Event):void
-
{
-
this.addChild($evt.target.content);
-
-
trace("IMG WIDTH: " + $evt.target.width + "\nIMG HEIGHT: " + $evt.target.height);
-
}
-
-
function tracePercentLoaded($evt:ProgressEvent):void
-
{
-
trace("PERCENT LOADED: " + Math.floor(($evt.bytesLoaded / $evt.bytesTotal) * 100));
-
}
As you can see in this particular example, I'm using the INIT event to listen to when the file has loaded (at which point I have access to things like the width and height of the loaded image) and the PROGRESS event where I have access to the bytesLoaded and bytesTotal properties that I can use to build preloaders and such. Keep in mind when using percentages to scale stuff that it is now based on 0 to 1, so a 50% scale would be written as .5. Therefore, you no longer have to multiply by 100 when you divide bytesTotal by bytesLoaded. The catch there is that you DO have to multiply by 100 if you want to display a percentage value in a text field, like 50% loaded. Just something to think about when making your preloaders. AS3 likes to keep you on your toes.
If you found this post useful, please consider leaving a comment, subscribing to the feed, or making a small donation.











No Comments
No comments yet.
Leave a comment