AS3覚え書き3 :グラフィクス

絵を描くにはSpriteクラスのgraphicsプロパティを利用します。
簡単なSampleクラスを例にとって基本的な図形を描いてみます。

package
{
	import flash.display.Sprite;

	public class Sample extends Sprite
	{
		public function Sample():void
		{
			myDrawRect();
			myDrawRoundRect();
			myDrawCircle();
			myDrawEllipse();
			myDrawLine();
			myDrawCurve();
		}
		public function myDrawLine():void
		{
			//描画	
		}
		public function myDrawCurve():void
		{
		}
		public function myDrawRect():void
		{
		}
		public function myDrawRoundRect():void
		{
		}			
		public function myDrawCircle():void
		{
		}
		public function myDrawEllipse():void
		{
		}	
	}
}

直線

moveToで指定xy座標に移動して、lineToで終端のxy座標まで直線を引きます。

public function myDrawLine():void
{
	this.graphics.lineStyle(3,0xCC00FF);
	this.graphics.moveTo(30, 50);
	this.graphics.lineTo(50, 80);	
}

曲線

直線のときと同様にmoveToで指定xy座標に移動して、curveToで曲線を描きます。
curveToの引数は、最初の2つがコントロールポイント、残りが終端の点(アンカーポイント)です。

public function myDrawCurve():void
{
	this.graphics.lineStyle(3,0xCCAAFF);
	this.graphics.moveTo(150, 150);
	this.graphics.curveTo(50, 80, 80 , 130);
}

長方形

引数はx座標,y座標,幅,高さです。lineStyleを併用すると輪郭を描くこともできます。

public function myDrawRect():void
{
	this.graphics.beginFill(0xFFAACC);
	this.graphics.drawRect(0, 0, 100, 50);
	this.graphics.endFill();
}

角丸長方形

同じく引数はx座標,y座標,幅,高さです。最後に角の半径を指定します。

public function myDrawRoundRect():void
{
	this.graphics.beginFill(0xAAAAFF);
	this.graphics.drawRoundRect(20, 200, 80, 80, 20);
	this.graphics.endFill();
}		

中心座標、半径を指定します。

public function myDrawCircle():void
{
	this.graphics.beginFill(0xFFAACC);
	this.graphics.drawCircle(100, 100, 50);
	this.graphics.endFill();
}

楕円

中心座標、x方向幅、y方向高さを指定します。

public function myDrawEllipse():void
{
	this.graphics.beginFill(0xFFCCCC);
	this.graphics.drawEllipse(200, 100, 30, 120);
	this.graphics.endFill();
}

グラフィクスの消去

clearメソッドを使います。

this.graphics.clear();