2008年8月12日 星期二

[Sample] 漸近式載入圖片 AS3 程式碼

因為有人寫信問要如何才能漸近地載入圖片(Progressvie Loading:載入一張之後再載入下一張),所以寫了一個AS範例程式碼(點我下載),說明都在註解裡,概念上只是入門的Recursive呼叫和Array Index的應用而已,自己參考看看摟:




package
{
 import flash.display.Loader;
 import flash.display.MovieClip;
 import flash.display.DisplayObject;
 import flash.events.Event;
 import flash.net.URLRequest;
 public class Sample_ProgressiveLoading extends MovieClip
 {
  private var myFileUrlArr:Array;
  //用這個loadedCount變數來記錄目前載到第幾個檔案
  private var loadedCount:uint = 0;

  public function Sample_ProgressiveLoading()
  {
   //假設你知道所有要下載的檔案總共有幾個: myFileUrlArr中我設了3張圖檔URL要下載(當然也可以是Swf)
   myFileUrlArr = new Array("picture_1.jpg","picture_2.jpg","picture_3.jpg");
   //把第1張圖在Array中的位置(Array從0開始)傳給loadTargetPicture(), 指示它去把第1張圖抓下來
   loadTargetPicture(loadedCount);
  }

  //準備變數給loadTargetPicture()使用
  private var urlLoader:Loader;
  private var pictureUrl:URLRequest;
  private function loadTargetPicture(fileArrIndex:uint):void
  {
   urlLoader = new Loader();
   //到myPictureArr中去取的在fileArrIndex位置的圖片URL資料給URLRequest;
   pictureUrl = new URLRequest(myFileUrlArr[fileArrIndex]);
   //先註冊Event再去執行load
   urlLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
   urlLoader.load(pictureUrl);
    //將loadedPicCount+1,指到下一張
   loadedCount++;
  }

  private function completeHandler(event:Event):void
  {
   //Event觸發到這個function表示目標圖已經載完, 用 content 取出載入的照片給 myPicture
   //這裡的 e.target 就是我們的 urlLoader.contentLoaderInfo
   //因為你把 event 註冊給它,所以 target 就是指它。

   var myPicture:DisplayObject = DisplayObject(event.target.content);

   //這裡看你想怎麼設定你載入的這"單一張"圖片(或Swf)隨便你
   myPicture.x = loadedCount*100;
   myPicture.y = loadedCount*100;
   this.addChild(myPicture);

   //最後再次呼叫loadTargetPicture(), 因為我們在上一次的loadTargetPicture中
   //把 loadedPicCount+1 了,所以圖片已經指到還沒下載的那一個檔案...

   if(loadedCount<myFileUrlArr.length) //判斷是不是最後一張(小於總張數)
   {
    //如果小於總張數, 就再去執行 loadTargetPicture() 載入下一張
    loadTargetPicture(loadedCount);
   }
  }
 }
}


P.S:上面的程式碼有經過HTML編排,建議直接下載原始碼。另,這個範例程式有個不算小的Bug,就是如果其中有一個檔案沒有成功下載(自然沒去觸發到completeHandler()),那後面的檔案也都不會下載了...這部分就請自己想辦法摟~(逃)

沒有留言: