封装加载xml文件和图片的方法,方便以后使用
注意:在加载时一定要进行错误处理
1 /** 2 * 加载xml文件 3 * @param url 4 * @param callback 5 * protected function init(event:FlexEvent):void 6 { 7 LoaderHelper.loadXML( "test.xml", onXMLLoaded ); 8 } 9 10 private function onXMLLoaded(xml:XML):void 11 { 12 trace( xml.toString() ); 13 } 14 * 15 */ 16 public static function loadXML(url:String, callback:Function):void 17 { 18 var loader:URLLoader = new URLLoader(); 19 loader.load( new URLRequest( url ) ); 20 //处理加载错误 21 loader.addEventListener(IOErrorEvent.IO_ERROR, onError); 22 loader.addEventListener(Event.COMPLETE, function(event:Event):void{ 23 callback( new XML( loader.data ) ); 24 } ); 25 } 26 27 /** 28 * 加载图片 29 * @param url 30 * @param callback 31 * 32 * protected function init(event:FlexEvent):void 33 { 34 LoaderHelper.loadImage( "test.png", onImageLoaded ); 35 } 36 37 private function onXMLLoaded(xml:XML):void 38 { 39 trace( xml.toString() ); 40 } 41 */ 42 public static function loadImage(url:String, callback:Function):void 43 { 44 var loader:Loader = new Loader(); 45 loader.load( new URLRequest( url ) ); 46 //处理加载错误 47 loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onError); 48 loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(event:Event):void{ 49 callback( Bitmap( loader.content ).bitmapData ); 50 } ); 51 } 52 53 /** 54 * 加载错误 55 * @param event 56 * 57 */ 58 protected static function onError(event:IOErrorEvent):void 59 { 60 trace(" urloader error...."); 61 62 }
使用方法
1 protected function init(event:FlexEvent):void 2 { 3 LoaderHelper.loadXML( "mySpritesheet.xml", onXMLLoaded ); 4 LoaderHelper.loadImage( "mySpritesheet.png", onImageLoaded ); 5 } 6 7 private function onXMLLoaded(xml:XML):void 8 { 9 trace( xml.toString() ); 10 } 11 12 private function onImageLoaded(bd:BitmapData):void 13 { 14 var image:Image = new Image(); 15 image.source = new Bitmap( bd ); 16 addChild( image ); 17 }