Pay for Hesitation: Removing drawing with clear

Pages

2008年3月28日 星期五

Removing drawing with clear

ActionScript的drawing跟java似乎有些不同,
在java中,graphics的重畫程序是: update()-> paint()-> repaint()or paintComponet()
其中在update()中,會先自動清除graphics的content,再重畫content。

如果不想清除之前的content,就需自己overwirte掉update(),讓它直接call paint()。
那麼每次重畫,content就不會清除之前的content,而是在content中加上新的shape,
所以content會隨著重畫的次數逐漸變大,效能會愈吃愈重。
詳請可以參考下列網址:
http://www.cs.clemson.edu/~cs428/resources/java/tutorial/JTGraphEx.html

這裡要說的是,actionscript預設的drawing動作與java似乎是相反的。
當sprite.graphics.drawXXX();
它便在sprite的graphics content中加入此shape,並自動在每個frame進行重畫。

所以千萬別在ENTER_FRAME event handler中使用graphics.drawXX(),
如下:
addEventListener(Event.ENTER_FRAME, onEnterFrame);

public function onEnterFrame(event:Event):void {
   graphics.drawCircle(x+1,y+1,r);
}

這樣在每個frame,都會在sprite的graphics content中增加一個circle shape,直到sprite的graphics content爆炸。

如果要模仿java在重畫前先清除之前的graphics content,就需先呼叫graphics.clear();
如:
public function onEnterFrame(event:Event):void {
   graphics.clear();
   graphics.drawCircle(x+1,y+1,r);
}

最後用下面這段描述做結語:
Use of the clear method has an important and somewhat unexpected effect on drawing efficiency. In the drawing API, it happens that the more you draw in a particular movie clip, the slower it goes. For a few dozen shapes, the slowdown is not noticeable, but little by little, each new shape takes longer and longer to draw. Even if the new shape completely covers and obliterates everything else, the vector information for those older shapes is still there and will be completely redrawn each time. This can be important in animation, where you are redrawing almost the same thing over and over. Using clear handles this by completely removing all prior vector information from the clip.

沒有留言: