I have a class (ImageLoader) that extends Sprite container and loads an external image to its instance. When i instantiate an object of this class from another (Main) class i want to have the dimensions (width, height) of the loaded image being known to this (Main) class. It seems that is difficult for me as the dimensions are known after the image compete loaded. But i don't know how to pass this information from completeHandler event handler to the Main class. Any ideas?
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
private const img1:String = "pic1.jpg";
private const img2:String = "pic2.jpg";
private var myImg1:ImageLoader;
private var myImg2:ImageLoader;
public function Main():void
{
myImg1 = new ImageLoader( img1 );
myImg1.cacheAsBitmap = true;
myImg1.addEventListener(ImageLoader.COMPLETE, onImageLoadComplete);
addChild( myImg1 );
}
private function onImageLoadComplete(evt : Event) : void
{
trace (ImageLoader(evt.currentTarget).getWidth());
trace (ImageLoader(evt.currentTarget).getHeight());
}
}
}
package
{
import flash.display.Sprite;
import flash.display.Loader;
import flash.events.Event;
import flash.net.URLRequest;
public class ImageLoader extends Sprite
{
private var loader:Loader;
private var iWidth:int;
开发者_运维知识库private var iHeight:int;
public static const COMPLETE : String = "complete";
public function ImageLoader( name:String ):void
{
loader = new Loader();
loader.contentLoaderInfo.addEventListener( Event.COMPLETE, completeHandler );
var request:URLRequest = new URLRequest( name );
loader.load( request );
}
public function getWidth():int
{
return iWidth;
}
public function getHeight():int
{
return iHeight;
}
private function completeHandler( event:Event ):void
{
iWidth = event.target.content.width
iHeight = event.target.content.height;
/* dispatcher MUST be after dimension computations */
dispatchEvent(new Event(ImageLoader.COMPLETE));
this.addChild( loader.content );
}
}
}
You can get the width and height of the image using the ImageLoader object public functions getWidth
and getHeight
but you need to know when the load is complete, so you could dispatch a event from ImageLoader completeHandler, like:
// declare public static constant
public static const COMPLETE : String = "complete";
// inside complete handler
dispatchEvent(new Event(ImageLoader.COMPLETE));
done with this you can now listen to this event from your Main class like this:
myImg2 = new ImageLoader( img2 );
myImg2.addEventListener(ImageLoader.COMPLETE, onImageLoadComplete);
// inside onImageLoadComplete handler you can read the width and height:
private function loadComplete(evt : Event) : void
{
trace (ImageLoader(evt.currentTarget).getWidth());
trace (ImageLoader(evt.currentTarget).getHeight());
}
精彩评论