Tuesday, December 29, 2009

Flex Image Centering

I was trying to get an image that was scaled to be centered on the screen and realized that Flex has some issues doing this. Using horizontalCenter="0" verticalCenter="0" will not work because whether you set the width and height or the maxWidth and maxHeight the image will fill the whole space. So, it an image is taller than it is wide it will still be left aligned.

To fix this I came across guille’s blog and after reading the comment "Anyone got something cleaner" I gave it a shot.

Here is my fix.
I consider using the maxHeight and maxWidth to be the appropriate method and I assume that you would also like to stretch the image out to fill the box. If you set the maxWidth and maxHeight then you can use add the following as the compete listener ( complete="onImageComplete(event)" )
protected function onImageComplete( e:Event ):void
{
 var image:Image = e.target as Image;

 var ratio:Number = Math.min( image.maxWidth/image.contentWidth, image.maxHeight/image.contentHeight );
 image.width = ratio * image.contentWidth;
 image.height = ratio * image.contentHeight;
}


If you don't want the image to stretch out, then just add 1 as another argument into the min function. The ratio will never be greater than one and the image will never be made larger than it was.
protected function onImageComplete( e:Event ):void
{
 var image:Image = e.target as Image;

 var ratio:Number = Math.min( 1, image.maxWidth/image.contentWidth, image.maxHeight/image.contentHeight );
 image.width = ratio * image.contentWidth;
 image.height = ratio * image.contentHeight;
}

Working Example

Flex Image Centering Example

2 comments:

  1. Can you please post a complete Flex example? I'm too much of noob to see how this relates to the other sections of the MXML. Thanks.

    ReplyDelete
  2. I updated this post with a working example.

    Click the image to see it in action.
    Right Click the working Flex App to view source and download the source if you want.

    ReplyDelete