オブジェクトをBitmapに変換して軽量なオブジェクトとして扱うクラス

This movie requires Flash Player 9

オブジェクトBitmapに変換して
軽量なオブジェクトとして扱うクラスの使い方。

複雑な形状、パスが多いオブジェクトは描画時に多くのリソースが必要になるので
軽く扱う必要があります。

そこで継承するだけで勝手にBitmapに変換するクラスをつくっておくと何かと便利です。

 

ソース

package {
	import flash.display.*
	import flash.events.Event;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	public class BitmapSprite extends Sprite {
		private var _scr:Bitmap
		private var _bmd:BitmapData
		private var _rect:Rectangle
 
		/**
		 * autoCapture
		 */
		private var _autoCapture:Boolean
		public function set autoCapture(value:Boolean):void {
			_autoCapture = value;
		}
 
		public function BitmapSprite( autoCapture:Boolean = true ):void {
			addEventListener(Event.ADDED_TO_STAGE , addStage )
			_autoCapture = autoCapture;
		}
 
		private function addStage(e:Event):void {
			removeEventListener(Event.ADDED_TO_STAGE , addStage )
			if (_autoCapture) capture();
		}
 
		public function capture():void {
			if (!numChildren) return;
			_bmd = new BitmapData(width ,height , true , 0x00FFFFFF)
			_scr = new Bitmap (_bmd);
			_rect = this.getBounds (this);
			_bmd.draw (this , new Matrix ( 1, 0, 0, 1 , -_rect.x, -_rect.y) );
			var l:uint = numChildren;
			for (var i:int = 0; i < l; i++) removeChildAt(0);
			addChild(_scr);
			_scr.x = _rect.left;
			_scr.y = _rect.top
		}
 
 
	}
}

 

使い方

Flash IDEでライブラリからステージに配置する場合


オブジェクトの基本クラスに設定することで簡単に扱うことができます。

 

プログラムで配置する場合

var japan:BitmapSprite = new Japan()
japan.autoCapture=true
addChild( japan)

 

This movie requires Flash Player 9

複雑なベクタを複数配置して動かしても
Bitmapに変換されているので軽い。

 

as3にはcacheAsBitmapプロパティがありますが
rotationやalphaの変更では再描画されリソースを食うので、使いどころが限られるでしょう。

ベクタデータを画像として取り込む方法もありますが
swf自体の容量が増えてしまったり、修正が入ると再度取り込み直す必要があるので
この方法であれば、簡単に修正もできて便利です。

個人的には、お飾り用のSpriteのパスが多い場合に
画像化するために使っています。

Filed under AS3 · Tagged with

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!

You must be logged in to post a comment.