我有一个类(ImageLoader),它扩展Sprite容器并将外部图像加载到其实例。当我从另一个(Main)类实例化该类的对象时,我想让已加载图像的尺寸(宽度,高度)为此(Main)类所知。对于我来说似乎很难,因为在图像竞争加载后已知尺寸。但我不知道如何将这些信息从completeHandler事件处理程序传递给Main类。有什么想法吗?
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());
}
}
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 );
}
}
答案 0 :(得分:1)
您可以使用ImageLoader对象公共函数getWidth
和getHeight
来获取图像的宽度和高度,但是您需要知道加载何时完成,因此您可以从ImageLoader completeHandler调度事件,像:
// declare public static constant
public static const COMPLETE : String = "complete";
// inside complete handler
dispatchEvent(new Event(ImageLoader.COMPLETE));
完成此操作后,您现在可以从Main类中收听此事件:
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());
}