Thoughts and views expressed online by the staff at Aqua Media

Loading external images with ActionScript 3

One technique of loading external images is using the Loader class.

It's similar to the URLLoader class but the Loader class loads and displays loaded images and SWF content. The Loader class is a part of the DisplayObject class; it is capable of displaying content as well as loading it.

To load external images using the Loader class, you need to create an object of the Loader class.

var imgLoader:Loader = new Loader();

To load an image into the Loader Object, the load method of the Loader class is used, along with a URLRequest.

var imgLoader:Loader = new Loader();
imgLoader.load(new URLRequest('image.jpg'));

The LoaderInfo class also has events and event types that dispatch information about the progress of the load through the Loader class.

The code below traces a loaded message after the loader object has completed loading the image.

var imgLoader:Loader =  new Loader();
imgLoader.contentLoaderInfo.addEventListner(Event.COMPLETE,
loaderCompleteHandler);
 
function loaderCompleteHandler(e:Event):void{
   trace('Image has loaded.');
}
 
imgLoader.load(new URLRequest('image.jpg'));

At this point all you have done is loaded in the image to the Loader Object. For the loaded image to display you will need to add the Loader object to the display list.

addChild(imgLoader);

The complete source code looks like this.

var imgLoader:Loader =  new Loader();
imgLoader.contentLoaderInfo.addEventListner(Event.COMPLETE,
loaderCompleteHandler);
 
function loaderCompleteHandler(e:Event):void{
   trace('Image has loaded.');
   addChild(imgLoader);
}
 
imgLoader.load(new URLRequest('image.jpg'));

Now your ready to build a preloader in ActionScript 3. Let's build it.

Comments are closed.

Powered by Wordpress | A blog by Aqua Media