Part 2: Using LoaderInfo Events to create reusable ImageLoader Class
2 June
Posted by Jake Rutter
ActionScript 3.0, Flash
Yesterday I created a post called ActionScript 3.0 LoaderInfo Useful Events which outlined some useful events in ActionScript 3.0 that can be used to listen for when things are open, loading, and complete.
I used that knowledge to create a custom class which loads an image. I used events to listen for the opening of the the request, the download progress, and then the completion of the download. This is a basic class which can be applied to almost anything, although I kept it very basic for now. I plan to build upon this class over time until I have a reusable preloader class that I can apply to any project based off this code.
ImageLoader.as
-
package {
-
import flash.display.*;
-
import flash.text.*;
-
import flash.net.URLRequest;
-
import flash.events.*;
-
-
public class LoaderExample extends Sprite {
-
-
public var loaderStatus:TextField;
-
-
public function LoaderExample() {
-
//Create the Loader and add it to the display list
-
var loader:Loader = new Loader();
-
addChild(loader);
-
-
//Add the event handlers
-
loader.contentLoaderInfo.addEventListener(Event.OPEN, handleOpen);
-
loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, handleProgress);
-
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, handleComplete);
-
-
//Load the external image
-
loader.load( new URLRequest("image.jpg"))
-
}
-
-
private function handleOpen (event:Event):void {
-
trace("open");
-
loaderStatus = new TextField();
-
addChild(loaderStatus);
-
-
loaderStatus.x = 100;
-
loaderStatus.y = 100;
-
loaderStatus.text = "Loading: 0%";
-
-
}
-
-
private function handleProgress (event:ProgressEvent):void {
-
var percent:Number = event.bytesLoaded/event.bytesTotal * 100;
-
loaderStatus.text = "Loading:" + percent + "%";
-
loaderStatus.autoSize = TextFieldAutoSize.LEFT;
-
trace(percent);
-
}
-
-
private function handleComplete(event:Event):void {
-
trace("complete");
-
removeChild(loaderStatus);
-
loaderStatus = null;
-
}
-
}
-
}
To Instantiate this code, add the following code to the first frame of your flash file and make sure the class is saved in the same directory as the flash file.
-
import ImageLoader;
-
-
var images:LoaderExample = new LoaderExample();
-
addChild(images);










Red Said,
June 4, 2008 @ 3:12 pm
Nice work Jake. Clean and concise.