如何在 ActionScript 3 中的函数调用中加载和返回.png文件



ActionScript 似乎不支持同步加载 png。我尝试异步加载它,但是存在使您的函数等待加载完成的问题。我无法做到这一点。我尝试在 while 循环中调用 setInterval 和 setTimout,并在加载完成后中断,但我得到了一些非常神秘的行为。对于函数参数,我传递了一个名为 doNothing 的函数,它只是一个空函数。当我运行时,setInterval 或 setTimeout 会一遍又一遍,非常快。他们不会等待提供的时间再次呼叫。此外,什么都不做永远不会被调用。

这是我的代码:

private function getData(extension:String):Bitmap
{
    var loader:Loader = new Loader();
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onComplete);
    loader.contentLoaderInfo.addEventListener(ErrorEvent.ERROR, onComplete);
    loader.load(new URLRequest(baseDir + extension));
    while (bitmap == null)
    {
        var test:Number = setInterval(doNothing, 1000);
    }
    var ret:Bitmap = bitmap;
    bitmap = null;
    return ret;
}
function onComplete(event:Event):void
{
    bitmap = Bitmap(LoaderInfo(event.target).content);
}
function doNothing():void
{
    trace("did nothing");
}

while 循环在这里不好,因为它会导致客户端冻结(15 秒的冻结会引发错误)

建议的实现:

private var loader:Loader;
private var onSuccess:Function;
// onSuccess = function (bitmap:Bitmap) : void
// onFail = function (e:ErrorEvent) : void
private function getData(extension:String, onSuccess:Function, onFail:Function):void
{
    this.onSucess = onSuccess;
    loader = new Loader();
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
    loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onFail);
    loader.contentLoaderInfo.addEventListener(ErrorEvent.ERROR, onFail);
    loader.load(new URLRequest(baseDir + extension));
}
private function onComplete(event:Event):void
{
    bitmap = Bitmap(LoaderInfo(event.target).content);
    onSuccess.call(null, bitmap);
    dispose();
}
private function dispose():void
{
    loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
    loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, onFail);
    loader.contentLoaderInfo.removeEventListener(ErrorEvent.ERROR, onFail);
    this.loader = null;
    this.onSuccess = null;
}

最新更新