Friday, July 23, 2010

Importing external images using AS3

Today we will learn how to load an external image into flash using Actionscript 3 and then work with it.

Say, we need to load a picture from a site, change its size and place it in the upper left corner, placing it behind all existing objects on the stage. First we need to create a Loader:

var imageLoader:Loader = new Loader();

'Feed' it the url to the picture:

imageLoader.load(new URLRequest(""));

Instead of the code above you can also split it to a few smaller lines:

var picUrl:String = ""
var myUrl:URLRequest = new URLRequest(picUrl)

Now, if we add the picture to the stage using addChild method and then try to change its width and height or whatever, it won't work. The picture will be added, however it will remain the same size. Why? Because we make the changes before we actually load our picture.

So we need to make sure the changes are made only after the picture is loaded. Create a listener for our loader's contentLoaderInfo property, that calls a function when the picture is loaded and make changes to it (remember, we want our picture to be displayed behind all existing objects on the stage, thats why we use addChildAt):

imageLoader.contentLoaderInfo.addEventListener(Event.INIT, loadComplete)

function loadComplete(event:Event):void {
addChildAt(imageLoader, 0);

There you go!

This question was asked at the Newgrounds forums, so I decided to make a tutorial about it. Feel free to send me AS3 tutorial requests!

No comments:

Post a Comment