blog
{Some Little News}
VR
{Virtual Reality}
media
{Photos + Videos}
code
{Websites + Apps}
5core
{Five Core}
Resize and center image in Flex [AS3]
I went almost crazy some time ago trying to resize and center some images dynamically loaded into Flex, finally I found out that the key point was to consider the image.contentWidth instead of the image.width. This beacuse if you try to get the image.width as you load the image it will return the value 0. Here is the function I used:
[code lang="as3"]
protected function resizePic(event:Event):void{
//size of the container of my image
var w:Number = myContainer.width;
var h:Number = myContainer.height;
//container ratio
var wthMaxRatio:Number = w / h;
//set the image scalable
pic.scaleContent = true;
//check if it is bigger than our container
if (pic.contentWidth > w || pic.contentHeight > h)
{
// image ratio
var wthImgRatio:Number = pic.contentWidth / pic.contentHeight;
var scaleFactor:Number;
// check if it is a wide image
if (wthImgRatio > wthMaxRatio)
{
scaleFactor = w/pic.contentWidth;
//resize the image
pic.content.scaleX = scaleFactor;
pic.content.scaleY= scaleFactor;
//center the image
pic.content.y=(h-pic.contentHeight)/2;
pic.content.x=0;
}
// it is a high image
else
{
scaleFactor = h/pic.contentHeight;
pic.content.scaleX = scaleFactor;
pic.content.scaleY= scaleFactor;
pic.content.x=(w-pic.contentWidth)/2;
pic.content.y=0;
}
}
}
[/code]
If you have any better idea, please post a comment ;).






