The title could do with some improving – what I’m trying to say is that when subclassing UIComponent, any Image component instances need to be given an appropriate width/height. I have overlooked this time and time again, only to find that the image doesn’t appear – because it’s width and height are initialised to zero.

The following code will result in an image with zero width/height, so the image won’t show:

1
2
var img:Image = new Image();
img.source = "myfile.jpg";

Solutions:

  1. Assign specific values for width and height:
    1
    2
    
    img.width = 100;
    img.height = 100;
  2. Set the ‘scaleContent’ property to false – the image will then resize its container automatically, once it has loaded. Note that this technique has no effect if loading image from non-trusted domains!
    1
    2
    3
    4
    5
    
    img.scaleContent = false;
     
    // or, if loading cross-domain, provided a crossdomain policy file allows access
    img.trustContent = true;
    img.scaleContent = false;
  3. Use an event listener to detect when the image has finished loading, then assign the correct width and height. Again, this will only work if the image has been loaded from a trusted domain.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    img.addEventListener(Event.COMPLETE, onImageComplete);
     
    protected function onImageComplete(evt:Event):void
    {
        var img:Image = evt.target as Image;
        img.removeEventListener(Event.COMPLETE, onImageComplete);
        img.width = img.content.width;
        img.height = img.content.height;
    }

I’ve mainly blogged about it so I remember the next time I write some code – but maybe it will also help somebody else debug their missing image problems.

Tags: , ,