Thursday, 12 May 2011

Loading and resizing image

This is a simple task to achieve. The AS3 has already a component that does this, but if you want to keep your SWF footprint to a minimum, you must consider this solution.

Nothing to it, but I seem to keep always forgetting, since I don't deal with this problem very often.

But here it is for future reference.

First of all we will be using two classes. One is URLRequest, that will capture the HTTP request for a file with its url. The other is the Loader which is used to load external SWF or image files (PNG, JPG or GIF).

First of all import these two classes:

import flash.display.Loader;
import flash.net.URLRequest;

Then instantiate the Loader class outside any function, because we will need it to resize later on.

private var myLoader:Loader;


Inside the loadImage function instantiate the URLRequest class by giving it the file url you which (the url can be a relative path. In this case there's no need to place the HTTP protocol).


Associate the Loader with this URLRequest, and finally add it to the DisplayList.


private function loadImage(file:String):void{
     var myRequest:URLRequest = new URLRequest(file);
     myLoader = new Loader();
     
     myLoader.load(myRequest);
     addChild(myLoader);
}

loadImage("mypicture.jpg");

If you run this, you will see the image "mypicture.jpg" in the stage.

The next step is to scale the image. Try and write the following lines inside the previous function:

myLoader.width=20;
myLoader.height=40;

What happens? The image doesn't appear. So what's going on?

We are trying to scale an object when the object does not have any contents yet.

We have to listen to the myLoader object to see if it has already load the picture and then we can scale.

Write the previous function like this adding the line in red:


private function loadImage(file:String):void{
     var myRequest:URLRequest = new URLRequest(file);
     var myLoader:Loader = new Loader();
     myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, resizeImage);
     myLoader.load(myRequest);
     addChild(myLoader);
}

Don't forget to add the Event class on the import statements.

The function for resizing by now you should have guessed it:

private function resizeImage(evt:Event):void {
myLoader.width = 45;
myLoader.height = 40;
}

Simple, right?

Happy resizing.


2 comments: