views:

813

answers:

3

I have a dynamic layout, where an image is loaded into an HBox:

<mx:HBox ...>
    <mx:Image height="100%" .../>
</mx:HBox>

only the image's height is set on the image, so that it can take all the vertical space available, while its width is left undefined and I expect the width to scale accordingly with its height.

It turns out that the image's height is equal to its contentHeight, i.e. height scales properly; however, the image's width is still the same as measuredWidth (the image's original width), and is not scaled accordingly.

For example, if the image's original size is 800x600 and if the HBox is 300 in height, then image height will scale down to 300, however its width doesn't scale down to 400, instead it stays at 800.

I tried to add an event listener to explicitly set the image width:

<mx:Image id="img" height="100%" updateComplete="img.width=img.contentWidth;" .../>

It works only the first time the image is loaded, after that, if I use Image.load() to dynamically load different images, it stops working - the image width is set to 0.

Any help/advice will be highly appreciated.

A: 

Try to use <mx:Box /> or <mx:Canvas /> not <mx:HBox />.

As I understand, HBox has flexible width. It calculates width later as a sum of it children. The same with height in VBox.

zdmytriv
<mx:Box> didn't work either. I didn't try <mx:Canvas> because I need the HBox layout - I have to display some text right next to the image on its right.
Tong Wang
A: 

try adding: maintainAspectRatio="true"


Update 1: In reply to your comment, this Is what you are looking for, as you can see in the example here. Maintaining the aspect ratio implies keeping the relation between width & height.

eglasius
This flag controls image distortion, which has nothing to do with my situation: the image itself still displays in the correct ratio, it is the Image control's width that is out of ratio. Thanks.
Tong Wang
@Tong see my update
eglasius
I know it's confusing, but we are talking about two sets of height/width here: one is the height/width of the image content, the other is the height/width of the image control. maintainAspectRatio defaults to true, so my image content is scaled properly in both height and width. However, the image control's width is not scaled with its height, causing the control to take additional "blank" horizontal space in an HBox.Thank you for your help and hope I explained it clear enough.
Tong Wang
A: 

Got the answer on Adobe forum. My solution was almost there, just need to use callLater(), like:

private function scaleImage():void {
    img.width = img.contentWidth;
}

updateComplete="callLater(scaleImage)"
Tong Wang
Really useful, gets me almost every time! Thanks
robmcm