开发者

Flex: Scale an Image so that its width matches contentWidth?

I have a dynamic layout, where an image is lo开发者_Python百科aded 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.


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)"


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.


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.


The observed behaviour is a documented bug, err, feature.
The image class documentation tells that the image height is the height of the scaled image, while the image width is the width of the unscaled image. And that his one should be used for layout.
I have no idea why height and width are handled differently and why a scaled image should waste space in its container, but that's how it has been coded.

The line

updateComplete="callLater(function():void{xxx.width=xxx.contentWidth;})"

(no need for a separate script function) cures this. But this really shouldn't be necessary at all.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜