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
[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;
}
}
}
[/as]

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.

[as]
import ImageLoader;

var images:LoaderExample = new LoaderExample();
addChild(images);
[/as]

2 Comments

Category ActionScript 3.0, Flash

You can follow any responses to this entry through the RSS 2.0 feed.

2 Responses to “Part 2: Using LoaderInfo Events to create reusable ImageLoader Class”

2 Comments so far
  1. Nice work Jake. Clean and concise.

  2. thank u very much..




XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

By submitting a comment here you grant Jake Rutter – Front-End Developer and Designer, CSS, JavaScript and jQuery, PHP, Wordpress, Expression Engine, Magento a perpetual license to reproduce your words and name/web site in attribution. Inappropriate comments will be removed at admin's discretion.