PDA

View Full Version : Can't load external png Flex / AS3


HeadBanger606
06-27-2011, 12:58 PM
I have been trying for a week now to write a program that reads an external image file "png" and loads and displays it on screen. As far as I can tell this is how I should be doing it :


<?xml version="1.0" ?>

<mx:Application xmlns:mx="mxml" autoLayout="false">

<mx:Script>
<![CDATA[

import flash.display.*;
import flash.net.URLRequest;
import flash.events.Event;

public var container:Sprite = new Sprite();
public var imgLdr:Loader = new Loader();
public var imgURL:String = "img/enemy.png";
public var imgURLReq:URLRequest = new URLRequest(imgURL);

public function load_img():void {
imgLdr.load(imgURLReq);
imgLdr.contentLoaderInfo.addEventListener(Event.CO MPLETE,imgLoaded);
addChild(container);
}

public function imgLoaded(event:Event):void {
container.addChild(imgLdr);
}


]]>
</mx:Script>
<mx:Button id="test_btn" click="load_img()" label="Load Image" />
</mx:Application>


Nothing.. zilch. No errors, no image. Nothing. What am I doing wrong? I need to do it using action script, I'm working on a game engine and I need to dynamically add an image whenever I instantiate an enemy. But I can't even get this simple test to work?!? Thanks for any help.

venkatsnet
06-27-2011, 01:30 PM
public function load_img():void {
rawChildren.addChild(container);
imgLdr.load(imgURLReq);
imgLdr.contentLoaderInfo.addEventListener(Event.CO MPLETE,imgLoaded);
}

Barna Biro
06-27-2011, 01:43 PM
Depending on what Flex version you are using, I'd set the loaded image as the source for either an Image or BitmapImage container and display that ( or you could use the Image container directly, specify the URL of the image as the source and it will handle the loading of image for you ). Since Flex works differently than your normal "pure AS 3.0 projects" do, you shouldn't really try adding raw Bitmaps to the display list directly. Instead, you need to wrap them ( as mentioned before, you could use Image or BitmapImage for that ) in a "Flex control" and display that instead.

HeadBanger606
06-28-2011, 11:16 AM
Thank you so much, the rawChildren.addChild made it work. Duh, I'm reading a little more about rawChildren right now so I fully understand it. I've been beating my head off the desk for the last week.

Edit :
I added a Canvas control and added my images to that instead of straight to the application and everything works exactly how I need . Awesome! Thanks guys.

rattleheadmegafan
06-30-2011, 05:53 PM
Looks like you found a solution but I usually do this:


[Bindable]
[Embed(source="/assets/logo.png")]
private var LOGO:Class;



<mx:Image source="{ LOGO }" />


to display images.

HTH,
http://blog.air4android.com