[英]Asynchronous image loading in AS3
我知道圖像將在AS3中異步加載,並且應該使用事件和事件偵聽器來處理同步。
因此,在一個簡單的情況下,它看起來像這樣:
var loader : Loader = new Loader();
var im_file: URLRequest = new URLRequest ("imfile.png");
loader.load(im_file);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loading_complete);
function loading_complete (e : Event) : void
{ // ... do smt with your loaded data // }
我想做的是有一個PreLoader類,它將預先加載我需要的所有圖像。 在這種情況下,加載完成后如何讓所有其他類知道?
我是否派遣活動? 在這種情況下,最佳做法是什么?
提前致謝,
普拉斯卡頓
您最有可能想要創建隊列並將圖像路徑添加到隊列。 然后,在完成每個圖像的加載之后,您進入隊列中的下一項。 加載所有圖像后,您將調度COMPLETE事件或類似的事件,以通知您的應用程序已完成。
檢查QueueLoader或Casalib以了解它們如何實現單個或批量圖像加載。
除了@Boon提供的答案外,這就是如何實際設置圖像隊列的方法。
首先,您需要一個列表,其中將存儲仍需要加載的所有圖像。 這使您可以輕松定義所需的圖像。 可以是“隊列”:
var queue:Array = [
"http://interfacelift.com/wallpaper/previews/03177_orionnebulaintheinfrared@2x.jpg",
"http://interfacelift.com/wallpaper/previews/03175_purpleclouds@2x.jpg",
"http://interfacelift.com/wallpaper/previews/03173_goodmorning2013@2x.jpg"
];
接下來要做的是設置我們正在做的事情的“核心”方法。 它將處理加載下一張圖像,並在隊列為空時通知我們。 看起來像這樣:
function loadNext():void
{
if(queue.length > 0)
{
// Notice here that we use .pop() on the queue, which will select and
// remove the last item from queue.
var req:URLRequest = new URLRequest( queue.pop() );
var photo:Loader = new Loader();
photo.load(req);
photo.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
}
else
{
// The queue is finished - dispatch an event or whatever you fancy to
// let the rest of the application know we're done here.
trace("Queue finished.");
}
}
然后當然還有我們的監聽器功能來處理已加載圖像的完成。 請注意,這里我們稱為loadNext()
-這是僅在當前加載的圖像完成后才開始在隊列中加載下一個圖像的關鍵。
function loadComplete(e:Event):void
{
addChild(e.target.content as Bitmap);
// Begin loading next image in the queue.
loadNext();
}
當然,要開始該過程,我們只需使用它,它可以立即通知我們如果隊列為空,隊列已完成,或者開始按順序加載圖像。
// Start loading the queue.
loadNext();
附加/整理:
如果您希望能夠回收此代碼或整理一下代碼,則可以輕松地將其放入類中。 該類可以稱為ImageQueue
,其結構將包含上述queue
數組, loadNext()
方法和loadComplete()
方法。 它還可以具有add()
方法,用於以一種更簡潔的方式將圖像最初添加到隊列中。
這是該課程的基礎,如果您有興趣,可以結束學習:
public class ImageQueue
{
private var _queue:Array = [];
public function add(image:String):void{ }
public function loadNext():void{ }
private function _loadComplete(e:Event):void{ }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.