package com.mindfock.blog {

[Learn] How to load images/swf’s in AS3

Posted: April 16th, 2008 | Author: John del Rosario | Filed under: AS 3.0, Learn, Programming and Development | Tags: , , , , | No Comments »

I am in the process of converting from AS2 to AS3 right now, so I am going to try my best to post everything I learn in this blog. It might help others out there who are still also in the process of converting. To those who aren’t, you should. :-P

This time it is about loading external images/swf’s.

In AS3, there are several types of DisplayObjects you could use to display on the stage (thus the name), along with MovieClips, Sprites(simple movieclips), Bitmaps(for bitmap data) and Loaders.
The Loader object is obviously what we would use to load these external visual data.

Basically, the Loader is just like a MovieClip, since they have a common superclass (well actually MovieClip is derived from Sprite, which is a sibling of Loader). It’s a like a MovieClip that could load objects. So, if you are coming from AS2, it would make things easier to think of it as just a MovieClip.

So, to load an image named “image.jpg”, first you need to create the Loader object. In the first frame of your timeline:

var loader:Loader = new Loader();

Now you need the url of the image to load it. The Loader object has a load() method that takes a URLRequest parameter. It’s just a class that handles url’s very well. Heh, I don’t really know much about it, you could read more of it in documentation.

var imageUrl:URLRequest = new URLRequest("image.jpg");

Now that we have our Loader object and our URLRequest, we could now load our image. It’s just simply calling the load() method of Loader and passing our URLRequest as argument.

loader.load(imageUrl);
addChild(loader);

After loading and adding it to the stage, you could do anything with it as you please.

loader.x = 50;
loader.alpha = .5;

Of course, you would want to have preloading for this kind of stuff. And yes, the Loader object generates similar events to the MovieClipLoader object we so loved in AS2. But all this happens very differently in AS3. All the information about the object being loaded is being held by a LoaderInfo object inside the Loader object.

So here is the code that traces the amount of kilobytes loaded adds the Loader object to the stage if loading is completed.

loader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loading);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);

function loading(e:Event):void{
trace(loader.contentLoaderInfo.bytesLoaded);
}

function loadComplete(e:Event):void{
trace("loaded");
addChild(loader);
}

Hope this post helps others who are still starting to move to AS3. A lot has changed between the two, but AS3 is definitely the better one.



Leave a Reply