Flex 4取Spark Bitmap Image组件内部source的实际大小

众所周知Flex 4使用BitmapImage组件来显示位图图像,其fillMode属性w可以为clip, repeat, scale由BitmapFillMode类提供。设置为BitmapFillMode.CLIP时,位图在区域的边缘处结束。设置为BitmapFillMode.REPEAT时,位图将重复以填充区域。设置为BitmapFillMode.SCALE时,位图将拉伸以填充区域。默认值为BitmapFillMode.SCALE。

  所以我们的原始位图大小就可能由于fillMode值的不同而被BitmapImage改变。那么怎么才能取到原始位图的width和height呢?其实分几种情况讨论:

1. 使用Loader下载后射入BitmapImage的source中并对BitmapImage设置了width和height属性

取法:要用source.width和source.height来取,就能正确取得原始位图的Size。

原因:Loader下载下来的content是一个Bitmap。

2. 直接用Embed绑入BitmapImage的source中并对BitmapImage设置了width和height属性

取法:要用(new source).width和(new source).height来取,才能正确取得原始位图的Size。

原因:用Embed绑入的是一个Class。

3. 用scale来缩放BitmapImage而不是对BitmapImage设置width和height属性

取法:无论是那种source直接取BitmapImage的width和height就是原始位图的Size。

原因:scale不改变原始大小。

说了这么多有点枯燥了,来看个例子吧:

<?xml version="1.0" encoding="utf-8"?>

<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 

  xmlns:s="library://ns.adobe.com/flex/spark" 

  xmlns:mx="library://ns.adobe.com/flex/mx"

  creationComplete="creationCompleteHandler(event)"

  backgroundColor="#000000">

<fx:Script>

<![CDATA[

import mx.events.FlexEvent;

protected function creationCompleteHandler(event:FlexEvent):void {

var loader:Loader = new Loader();

loader.load(new URLRequest("da187070s.jpg")); 

loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function():void {

image.addEventListener(FlexEvent.UPDATE_COMPLETE, mediaUpdated);

image.source = loader.content;

});

const tmpImg:Object = new img.source;

ps2.text += tmpImg.width + ' * ' + tmpImg.height;

function mediaUpdated():void {

image.removeEventListener(FlexEvent.UPDATE_COMPLETE, mediaUpdated);

ps1.text += image.source.width + ' * ' + image.source.height;

}

}

]]>

</fx:Script>

<s:HGroup horizontalCenter="0" verticalCenter="0" gap="17" fontSize="15" color="#FFFFFF">

<s:VGroup>

<s:Label text="Use Loader &amp; Set size :" fontWeight="bold"/>

<s:Label id="ps1" text="Practical Size : "/>

<s:Label text="{'Current size : '+image.width+' * '+image.height}"/>

<s:BitmapImage id="image" smooth="true" width="210" height="149.1"/>

</s:VGroup>

<s:VGroup>

<s:Label text="Use Embed &amp; Set scale :" fontWeight="bold"/>

<s:Label id="ps2" text="Practical Size : "/>

<s:Label text="{'Current size : '+img.width+' * '+img.height}"/>

<s:BitmapImage id="img" source="@Embed('da187051s.jpg')"  smooth="true" scaleX="0.35" scaleY="0.35"/>

</s:VGroup>

</s:HGroup>

</s:Application>

posted @ 2012-01-31 16:53  lovecd  阅读(793)  评论(0编辑  收藏  举报