April 2007 Archives

Loading external images in AS3

| | Comments (7) | TrackBacks (0)
I thought I would post this as all the tutorials I found about loading external images in AS3 were either not working or very confusing. So here is a quick way of loading external images. For the sake of this example I will show only the methods needed in a class. First, we need to create a new Loader object. We then need to add an event listener to check when the image has loaded completely and add it to the display list. So lets start with creating the new object and adding the event.

	public function loadImage():void
	{
		var loader:Loader = new Loader;
		loader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoaded);
		loader.load(new URLRequest("assets/sample.jpg"));
	}

Next we need to create a method to deal with the event that will be dispatched when the image has completely loaded. This method takes one parameter which is an object of the Event class. It contains the data that we want, in order to display this image on the stage. Remember drawing items on the stage is a 2 part process in AS3, create and add to stage.

	private function imageLoaded(event:Event):void
	{
		var image:Bitmap = new Bitmap(event.target.content.bitmapData);
		addChild(image);
	}

I hope this helps some of you out there who have been in the process of migrating from AS2 to AS3, or just been playing around. Remember to import the necessary classes to deal with the event, loader and bitmap objects we used. Selah.