在Flex中需要加载网络图片时(jpg,png,gif等)可以使用URLLoader的相关方法,具体代码如下:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600" creationComplete="application1_creationCompleteHandler(event)">
<fx:Script>
<![CDATA[
import mx.controls.Image;
import mx.events.CloseEvent;
import mx.events.FlexEvent;
import mx.managers.PopUpManager;
import spark.components.Scroller;
import spark.components.TitleWindow;
import spark.components.VGroup;
import spark.layouts.HorizontalLayout;
private var imgWin:TitleWindow;
private var urlLoader:URLLoader = new URLLoader();
protected function application1_creationCompleteHandler(event:FlexEvent):void
{
var urlReq:URLRequest = new URLRequest("http://www.baidu.com/img/bdlogo.gif");
urlLoader.dataFormat = URLLoaderDataFormat.BINARY;
urlLoader.load(urlReq);
urlLoader.addEventListener(Event.COMPLETE, completeHandler);
}
private function completeHandler(event:Event):void {
var fileName:String = "远程图片";
imgWin = new TitleWindow();
var layout:HorizontalLayout = new HorizontalLayout();
layout.horizontalAlign = "center";
layout.verticalAlign = "middle";
imgWin.layout = layout;
imgWin.addEventListener(CloseEvent.CLOSE,function():void{
PopUpManager.removePopUp(imgWin);
});
imgWin.width = 800;
imgWin.height = 480;
imgWin.title = fileName;
var img:Image = new Image();
img.source = urlLoader.data;
// 这里使用 img.load(urlLoader.data);也可以
img.name = fileName;
img.addEventListener(Event.COMPLETE,onImageLoadComplete);
var scroller:Scroller = new Scroller();
scroller.percentHeight = 100;
scroller.percentWidth = 100;
var g:VGroup = new VGroup();
g.horizontalAlign = "center";
g.verticalAlign = "middle";
g.addElement(img);
scroller.viewport = g;
imgWin.addElement(scroller);
}
private function onImageLoadComplete(e:Event):void{
var img:Image = e.currentTarget as Image;
// Alert.show('img width:'+img.width+',height:'+img.height+','+img.contentWidth+","+img.contentHeight);
imgWin.width = img.contentWidth <= 750 ? 800 : (img.contentWidth+50);
imgWin.height = img.contentHeight <= 430 ? 480 : (img.contentHeight+50);
// imgWin.title = img.name;
PopUpManager.addPopUp(imgWin, this, true);
PopUpManager.centerPopUp(imgWin);
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
</s:Application>