之前寫了一篇displayObject轉成bitmap的文章,最近在整理電腦時,將以前做過的測試整理,因此將其轉成工具類別便於日後使用,程式碼如下:
package com.tools.graphics
{
import flash.display.Bitmap;
import flash.display.BitmapData;
import flash.display.DisplayObject;
import flash.display.Loader;
import flash.display.LoaderInfo;
public class LoaderToBitmap
{
/**
*建構式參數使用一個內隱類,避免使用者建立實體,
*因為as3不能使用private給予建構式的關係,
*但是使用者若給予null之後依然會被執行super()的建構式,所以無法避免得很完全。
*/
public function LoaderToBitmap(dontCreate:DontCreate)
{
}
static public function cloneBitmap(display:DisplayObject):Bitmap
{
var bitmap:Bitmap = new Bitmap(cloneBitmapData(display));
return bitmap;
}
static public function cloneBitmapData(display:DisplayObject):BitmapData
{
var bitMapData:BitmapData = new BitmapData(display.width , display.height);
bitMapData.draw(display);
return bitMapData;
}
}
}
class DontCreate
{
public function DontCreate()
{
}
}
//在Flex4 SDK環境下,使用範例
<?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" minWidth="955" minHeight="600"
applicationComplete="application1_applicationCompleteHandler(event)"
>
<fx:Script>
<![CDATA[
import com.tools.graphics.LoaderToBitmap;
import mx.events.FlexEvent;
private var _loader:Loader;
//記得在對應路徑的資料夾裡放入imag01.jpg的圖片,不然測試會抓不到圖片
private var _url:String = "image/img01.jpg";
private var _request:URLRequest;
protected function application1_applicationCompleteHandler(event:FlexEvent):void
{
_loader = new Loader();
//注意是對loader的contentLoaderInfo做偵聽
_loader.contentLoaderInfo.addEventListener(Event.COMPLETE , loaderComplete);
_request = new URLRequest(_url);
//讀取圖片
_loader.load(_request);
//將loader加到畫面上
_loader_container.addChild(_loader);
}
private function loaderComplete(e:Event):void
{
var d:DisplayObject = (e.currentTarget as LoaderInfo).content;
if(d != null)
{
//將loader複製成一個bitmap使用
var bitMap:Bitmap = LoaderToBitmap.cloneBitmap(d);
_bitmap_container.addChild(bitMap);
}
}
]]>
</fx:Script>
<s:HGroup>
<s:Group>
<s:Rect id="background" width="100%" height="100%">
<s:fill>
<s:SolidColor color="#990000"/>
</s:fill>
</s:Rect>
<mx:UIComponent id="_loader_container" width="340" height="450"/>
</s:Group>
<s:Group>
<s:Rect x="0" y="0" radiusX="4" radiusY="4" height="100%" width="100%">
<s:stroke>
<s:LinearGradientStroke weight="1" scaleMode="normal" />
</s:stroke>
<s:fill>
<s:LinearGradient>
<s:entries>
<mx:GradientEntry color="0x999999"/>
</s:entries>
</s:LinearGradient>
</s:fill>
</s:Rect>
<mx:UIComponent id="_bitmap_container" width="340" height="450"/>
</s:Group>
</s:HGroup>
</s:Application>
沒有留言:
張貼留言