admin 发表于 2011-4-30 12:37:21

Flash动态加载外部图片

一、简介初学AS,做了一个从外部调用图片的例子。AS2.0中有MovieClip和全局中有loadMovie函数可以动态加载图片,但是这不是异步加载,而且没法知道图片大小。在AS3.0中,有Loader类来实现从外部载入swf和各种图片。
二、代码progress.visible =
false;
btnSubmit.addEventListener(MouseEvent.CLICK,btnSubmitClickHandler);
function btnSubmitClickHandler(e:MouseEvent) {
    loadPicture(ddlUrl.value);
}

var loader:Loader;
function loadPicture(url:String) {
    if(loader ==
null){
        loader =
new Loader();
    }else{
        loader.unload();
        txtAlert.text =
"";
    }
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE,completeHd);
    loader.contentLoaderInfo.addEventListener("ioError",errorHd);
    var request:URLRequest =
new URLRequest(url);
    var context:LoaderContext =
new LoaderContext(true);
    loader.load(request,context);
    progress.visible =
true;
}

var maxHeight:int
= container.height;
var maxWidth:int
= container.width;
function completeHd(e:Event) {
    txtAlert.text =
"* Load success!";
    var pic:Bitmap = loader.content as Bitmap;
    pic.smoothing =
true;
    var currentWidth:int
= loader.width;
    var currentHeight:int
= loader.height;
    if(currentWidth > maxWidth){
        currentWidth = maxWidth;
        currentHeight = currentWidth/loader.width * loader.height;
    }
    if(currentHeight > maxHeight){
        currentHeight = maxHeight;
        currentWidth = currentHeight/loader.height * loader.width;
    }
    loader.content.width = currentWidth;
    loader.content.height = currentHeight;
   
    loader.x = (maxWidth - currentWidth)/2;
    loader.y = (maxHeight - currentHeight)/2;
    container.addChild(loader);
    progress.visible =
false;
}
function errorHd(e:Event){
    progress.visible =
false;
    txtAlert.text =
"* Url is invalid, Please try again for another url!";
}
三、原理关键在于对Loader类的使用,Loader具有contentLoaderInfo属性,此属性是一个LoaderInfo类的实例,用来控制加载外部资源的进度,因此就可以在contentLoaderInfo上注册各种事件,这里只用了Complete事件,用于加载完成时调用。 Loader还具有content属性,Loader实例本身就是一个可视对象,content也是一个可视对象,如果加载的地址是一个图片的话,content是一个Bitmap对象,所以可以通过转型来使得载入的图片在缩小的时候消除锯齿,将Bitmap的smoothing属性设置为true即可。
页: [1]
查看完整版本: Flash动态加载外部图片