AS3:graphics.clear的必要性?

AS3: Necessity of graphics.clear?

我有一个每次调用时都会重绘 Shape 的函数

function drawIt():void {
  myShape.graphics.clear() //Is this necessary?
  myShape.graphics.beginFill(newColor);
  myShape.graphics.drawRect(0,0,w,h);
  myShape.graphics.endFill();
}

如果这个函数在我补间颜色时经常被调用,而我不是每次都执行 graphics.clear(),我最终会得到一大堆长方形相互重叠吗?增加一堆内存?

这是必要的,否则任何新绘图都会添加到前一个绘图之上。如果那不是您需要的效果,那么您需要调用 clear 来删除之前的任何绘图。此行为可用于裁剪先前绘图的一部分。你可以画一个矩形,比方说黑色,然后在上面画一个圆(相同颜色),结果就是裁剪。

底线:如果您不调用清除所有绘图,则会将它们叠加在一起。

要回答您的问题,请看一下这个简单的测试:

var init_memory:uint = System.totalMemory;

var shape:Shape = new Shape();
for(var i:int = 0; i < 1000; i++){
    shape.graphics.clear();
    shape.graphics.beginFill(0xff0000);
    shape.graphics.drawRect(0, 0, 10, 10);
    shape.graphics.endFill();
}

trace(System.totalMemory - init_memory);    // gives : 4096 (bytes)

现在让我们评论这一行:

//shape.graphics.clear();

我们得到:

trace(System.totalMemory - init_memory);    // gives : 102400 (bytes)

并且只有一种形状:

trace(System.totalMemory - init_memory);    // gives : 4096 (bytes)

我认为您不需要任何评论就可以理解为什么要使用 graphics.clear() ...

希望能帮到你。