views:

137

answers:

2

i'm trying to access the width and height of an image that is added to the stage via a custom LoadImage class. the trace results are 0 even though the image displays correctly. what is the problem?

//frame script

var image:LoadImage = new LoadImage("myImage.jpeg");
addChild(image);
trace(image.width);  //returns 0

//-------------------------

package
{
import flash.display.Sprite;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.Event;

public class LoadImage extends Sprite
    {
    public function LoadImage(imageURL:String)
        {
        //Load Image
        var imageLoader:Loader = new Loader();
        imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageHandler);
        imageLoader.load(new URLRequest(imageURL));
        }

    private function imageHandler(evt:Event):void
        {
        addChild(evt.target.content);
        }
    }
}
A: 

you're trying to get the width and height before the image is completely loaded? see this question for more detail.

nathan gonzalez
+1  A: 

If you're trying to access it right after you instantiate it, you don't have access to it's properties. You will have to make it event driven:

 class LoadImage loads image
 frame script listens for a complete event from LoadImage 
 LoadImage loads the image, once it has it's hands on it it dispatches the event
 frame script works with the data 

you need to make an event in LoadImage and once done in imageHandler, dispatch that. When you make your new LoadImage, set up the listener

var image:LoadImage = new LoadImage("myImage.jpeg");
image.addEventListener("complete", loadedImage); //or whatever you call the event

function loadedImage(evt:Event) {
   addChild( evt.target );
   trace(evt.target.content.width);  //returns 0
}
Dan Heberden
evt.target.content.width works fine, but my problem is accessing this from the frame script, not from within the class
TheDarkInI1978
That's like sending your girlfriend to the store for beer and immediately going to the fridge and expecting it there. You have to wait for her to get back and put the beer in the fridge. (see new answer)
Dan Heberden