0

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

这是我的代码:

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");
}
4

1 回答 1

0

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;
}
于 2012-07-08T15:23:10.273 回答