Flash AS3教程:ByteLoader類
2020-07-17 13:18:29
供稿:網(wǎng)友
前面介紹了ClassLoader類的技巧,請觀看更多關(guān)于Flash教程的內(nèi)容。
該類的主要功能是把swf,jpg,png,gif等文件以字節(jié)的形式加載進(jìn)來
以便于使用Loader.loadBytes方法,重復(fù)加載使用素材
如果圖片格式為jpg,并且是漸進(jìn)式格式j(luò)peg,那么該類還可以幫助你邊加載邊顯示
index.base.net.byteLoader類講解:
基本功能按字節(jié)加載圖片,swf等
構(gòu)造函數(shù)
public function ByteLoader(url:String = "")
如果傳入了參數(shù)url,則立即執(zhí)行加載!
load 加載方法
public function load(_url:String):void
開始加載,_url是加載的地址
updata 更新數(shù)據(jù)方法
public function updata():void
更新緩沖區(qū)的可讀字節(jié)
close 關(guān)閉方法
public function close():void
類使用完畢,清除所有無用的數(shù)據(jù),也可以用來強(qiáng)行關(guān)閉數(shù)據(jù)流,停止下載
data 屬性
public var data:ByteArray
返回加載的字節(jié)
url 屬性
public var url:String
返回加載的url
isLoad 屬性(只讀)
public function get isLoad():Boolean
返回是否有數(shù)據(jù)在加載
ProgressEvent.PROGRESS 事件
加載的過程中調(diào)度,并附帶加載情況
Event.COMPLETE 事件
加載完畢調(diào)度
例子:
import index.base.net.ByteLoader;
var bl:ByteLoader = new ByteLoader;
bl.load("http://www.xiaos8.com/uploads/pro/50preso3a2.swf");
bl.addEventListener(Event.COMPLETE,completeFun);
bl.addEventListener(ProgressEvent.PROGRESS,progressFun);
function completeFun(e:Event):void{
var loader:Loader = new Loader;
loader.loadBytes(bl.data);
addChild(loader);
bl.removeEventListener(Event.COMPLETE,completeFun);
bl.removeEventListener(ProgressEvent.PROGRESS,progressFun);
bl.close();
bl = null;
}
function progressFun(e:ProgressEvent):void{
trace(e.bytesLoaded);
//如果是漸進(jìn)式格式的jpeg圖片,那么在發(fā)布這個(gè)事件的時(shí)候讀取字節(jié),用Loader.loadBytes加載,就可以形成邊加載邊顯示
}
源代碼:
package index.base.net{
import flash.events.EventDispatcher;
import flash.events.ProgressEvent;
import flash.events.Event;
import flash.utils.ByteArray;
import flash.net.URLStream;
import flash.net.URLRequest;
public class ByteLoader extends EventDispatcher{
public var url:String;
public var data:ByteArray;
private var stream:URLStream;
public function ByteLoader(url:String = ""){
if(url != ""){
load(url);
}
}
//加載
public function load(_url:String):void{
url = _url;
data = new ByteArray;
stream = new URLStream;
stream.load(new URLRequest(url));
stream.addEventListener(Event.COMPLETE,completeFun);
stream.addEventListener(ProgressEvent.PROGRESS,progressFun);
}
//加載中
private function progressFun(e:ProgressEvent):void{
if(stream.bytesAvailable == 0) return;
updata();
dispatchEvent(e);
}
//加載完成
private function completeFun(e:Event):void{
stream.removeEventListener(Event.COMPLETE,completeFun);
stream.removeEventListener(ProgressEvent.PROGRESS,progressFun);
updata();
if(isLoad) stream.close();
dispatchEvent(e);
}
//更新數(shù)據(jù)
public function updata():void{
if(isLoad) stream.readBytes(data,data.length);
}
//清除數(shù)據(jù)
public function close():void{
if(isLoad) stream.close();
stream = null;
data = null;
}
//獲取是否有數(shù)據(jù)在加載
public function get isLoad():Boolean{
if(stream == null) return false;
return stream.connected;
}
}
}