Wednesday, 19 May 2010

Loading Bitmap images in Actionscript 3

This is a quick tip where I will load a bitmap image from the library onto the stage. Firstly, you need to import an image in Flash (File > Import > Import to Library). In the library, right click on the image and select ‘Properties’. Click on the Actionscript tab and click the ‘Export for Actionscript’. Give the Class the name ‘MyImage’ and click ok. In the Actionscript Panel add the following code.

var bmd:BitmapData = new MyImage(0,0);
var bp:Bitmap = new Bitmap(bmd);
addChild(bp);

The code above creates a new instance of the Bitmap and adds it to the display list. You can also write the code into one line like this.

var bp:Bitmap = new Bitmap(new MyImage(0,0));
addChild(bp);

If you want to load an image externally into a bitmap you need to use the Loader class like this.

var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
loader.load(new URLRequest('myimage.jpg'));

function imageLoaded(e:Event):void{
 var bitmap:Bitmap = Bitmap(e.target.content);
 addChild(bitmap);
}

The code creates a new instance of the Loader class, adds complete event to let you know when the image has loaded and takes the URLRequest object with the url of the image. The imageLoaded function add the Bitmap onto the stage using a reference to the loader’s content property.

0 comments:

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP