11-06-2009

Actionscript3 Scale loader content from/to center in AS3

When tweening, resizing / rescaling an image loaded with the as3 loader class in certain cases it looks neater if it rescales to the center of its parent.

Although pretty obvious in retrospect it took me a while to figure out how to align the Loader's content to the center, and not the top left of it's parent where it is placed by default.

To do this it the Loader.content of course needs to have the 0,0 coordinate as it's center which is done by repositioning the loader content in the handler for the Event.INIT event like so - (where 'loader' represents an instance of the Loader class).

var image = addChild(loader.content);
image.x -=	image.width/2
image.y -=	image.height/2
 

Example usage in class:

package nl.hardCode.loader
{
	import flash.display.*;
	import flash.events.*;
	import flash.net.*;
 
	public class BitmapLoader extends Sprite
	{
		protected var loader:Loader;
 
		function BitmapLoader(path){
			loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.INIT,initListener);		
			loader.load(new URLRequest(path));
		}
 
		function initListener(e:Event):void{ 
			var image = addChild(loader.content);
			image.x -= image.width/2
			image.y -= image.height/2
		}
	}	
}

Comments:

Your comment:

»

 

[x]