Popa Mihai

PopaMihai.com – Flex, Flash, AIR and ActionScript articles and tutorials

Image Width and Height Turn Out 0 After the Image is Loaded

one comment

After you load an image with Flex and add it to the stage most of the times you need the image width and height for manipulation.

If you use FlexEvent.CREATION_COMPLETE event to get the width and height these values will turn out to be 0. What you have to use is the FlexEvent.UPDATE_COMPLETE event to get the image width and height.

Here’s a small application that does that:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" verticalAlign="middle"
	backgroundColor="white" creationComplete="init()" viewSourceURL="srcview/index.html">
	<mx:Script>
		<![CDATA[
			import mx.events.FlexEvent;
			import mx.controls.Alert;
			import mx.controls.Image;
 
			private var img : Image;
 
			private function init() : void {
				img = new Image();
				img.source = "home.png";
				img.addEventListener( FlexEvent.UPDATE_COMPLETE, onUpdateComplete );
				img.addEventListener( FlexEvent.CREATION_COMPLETE, onCreationComplete );
				addChild( img );
			}
 
			private function onUpdateComplete( event : FlexEvent ) : void {
				Alert.show( 'widht: ' + img.width + '\n' + 
							'height: ' + img.height,
							'update complete' );
			}
 
			private function onCreationComplete( event : FlexEvent ) : void {
				Alert.show( 'widht: ' + img.width + '\n' + 
							'height: ' + img.height,
							'creation complete' );
			}
		]]>
	</mx:Script>
</mx:Application>

And here’s the resulting SWF:

You will notice that FlexEvent.UPDATE_COMPLETE event gets triggered twice in the application. That’s because Flex dispatches additional FlexEvent.UPDATE_COMPLETE events every time the size, position, etc of the component changes and the component has been updated.

View Source is enabled in the above example. To view the source files right click on the swf and choose “View Source” from the context menu.

Written by Popa Mihai

August 24th, 2010 at 11:57 pm

Posted in Flex

Tagged with ,

One Response to 'Image Width and Height Turn Out 0 After the Image is Loaded'

Subscribe to comments with RSS or TrackBack to 'Image Width and Height Turn Out 0 After the Image is Loaded'.

  1. Thx man! works great!

    John Maverick

    1 Dec 10 at 1:04 pm

Leave a Reply