一个简单的画板

Flex中画图,有两种方法:

1、直接在canvas中画

 

private function init():void{
	cav.graphics.lineStyle(1, 0x000000, 1, false);
	cav.graphics.lineTo(200, 200);
}
<mx:Canvas id="cav" width="300" height="300" />

 

2、在Sprite中画,然后将其添加到舞台中。所有显示对象都必须继承UIComponent类,但是Sprite并没有继承UIComponent,如果想显示Sprite,就先要把Sprite添加到UIComponent中,然后再添加到舞台中。

 

sprite = new Sprite();
sprite.graphics.lineStyle(1,0x000000,1,true);
sprite.graphics.lineTo(event.localX, event.localY);
ui = new UIComponent();
ui.addChild(sprite);
cav.addChild(ui);

 

下面例子实现了一个简单的画板,只实现了画线、撤销、还原、清屏等简单的部分功能,目的是研究Flex画板的原理。

 

private var sprite:Sprite;				//作画的载体
private var ui:UIComponent;				//包装Sprite,然后才能添加到舞台上
private var index:int = 0;				//作画的操作数,也是添加到舞台的每个对象的索引
private var flag:Boolean = false;		//表示鼠标是否按下
private var arr:Array = new Array();	//被撤销的对象列表,以备还原

/**
 * 按下鼠标,初始化画笔
 */
protected function cav_mouseDownHandler(event:MouseEvent):void
{
	sprite = new Sprite();
	sprite.graphics.clear();
	sprite.graphics.lineStyle(1,0x000000,1,true);
	sprite.graphics.moveTo(event.localX, event.localY);
	sprite.graphics.lineTo(event.localX, event.localY);
	ui = new UIComponent();
	ui.addChild(sprite);
	cav.addChildAt(ui, index++);
	flag = true;
}

/**
 * 如果鼠标按下,并滑动,开始画画
 */
protected function cav_mouseMoveHandler(event:MouseEvent):void
{
	if(flag == true){
		sprite.graphics.lineTo(event.localX, event.localY);
	}
}

/**
 * 停止画画
 */
protected function cav_mouseUpHandler(event:MouseEvent):void
{
	flag = false;
}

/**
 * 撤销
*/
protected function btnUndo_clickHandler(event:MouseEvent):void
{
	if(index <= 0){
		return;
	}
	arr.push(cav.getChildAt(--index));
	cav.removeChildAt(index);
}

/**
 * 还原
 */
protected function btnRedo_clickHandler(event:MouseEvent):void
{
	if(arr != null && arr.length > 0){
		cav.addChildAt(arr.pop(), index++);
	}
}

/**
 * 清屏
 */
protected function btnClear_clickHandler(event:MouseEvent):void
{
	if(index >= 0){
		cav.removeAllChildren();
		index = 0;
	}
	if(arr != null && arr.length > 0){
		arr.splice();
	}
}

<mx:VBox id="vb" width="100%" height="100%">		
	<mx:HBox>
		<mx:Button id="btnUndo" label="撤销" click="btnUndo_clickHandler(event)" />
		<mx:Button id="btnRedo" label="还原" click="btnRedo_clickHandler(event)" />
		<mx:Button id="btnClear" label="清屏" click="btnClear_clickHandler(event)" />
	</mx:HBox>
	<mx:Canvas id="cav" width="500" height="500" backgroundColor="#FFFFFF" 
			   mouseDown="cav_mouseDownHandler(event)"
			   mouseMove="cav_mouseMoveHandler(event)"
			   mouseUp="cav_mouseUpHandler(event)"/>
</mx:VBox>

你可能感兴趣的:(Flex,画板)