Tips:three ways to load an image file in Flex

 

Similar to a previous article How to load an image into our Flex application from URL(with source),the following source code shows three ways that how to load an image file.

Full code after the jump.

  1. <?xml version=”1.0″ encoding=”utf-8″?>
  2. <mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” applicationComplete=”InitApp()”>
  3. <mx:Script>
  4. <![CDATA[
  5. //the first way:it will build “image.jpg” file into swf ( after building into swf,the image.jpg file is NOT needed)
  6. [Bindable]
  7. [Embed(source=”image.jpg”)]
  8. private var imgClass:Class;
  9. //the second way
  10. private var _loader:Loader;
  11. private function InitApp():void{
  12. // source code of the first way
  13. _img.source = imgClass;
  14. //source code of the second way
  15. _loader = new Loader();
  16. //notice: NOT _loader.addEventListener,is  _loader.contentLoaderInfo.addEventListener
  17. _loader.contentLoaderInfo.addEventListener(Event.COMPLETE,function(e:Event):void{
  18. _img.source = e.currentTarget.content;
  19. });
  20. _loader.load(new URLRequest(encodeURI(“image.jpg”)));
  21. //the third way
  22. _img.source = “image.jpg”;  //Notice: set img autoLoad’s property to true
  23. //image.jpg file is needed by the second and the third way’s *.swf
  24. }
  25. ]]>
  26. </mx:Script>
  27. <mx:Image x=”51″ y=”62″ width=”298″ height=”245″ autoLoad=”true” id=”_img”/>
  28. </mx:Application>