在Flex Canvas上绘制正方形

时间:2009-12-23 22:58:55

标签: flex canvas drawrect

我正在尝试将一些代码写入Flex Canvas上的正方形动画图像。我的代码下面有问题,因为它变得越来越慢。我想我应该清除旧方块或其他东西。

我在下面做错了什么?:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init();">
<mx:Script>
<![CDATA[
public var ticker:Timer;

    public function init():void {

        ticker = new Timer(10);

        // This implements the timerEvent
        ticker.addEventListener(TimerEvent.TIMER, update);
        ticker.start();

        draw();
    }

    public function update(evt:TimerEvent):void {
        draw();
    }

    public function draw():void {
        var squareSize:uint = 10;
        var square:Shape = new Shape();

        square.graphics.beginFill(0xFFFFFF, 1.0);
        square.graphics.drawRect(0, 0, myCanvas.width, myCanvas.height);

        var i:int;
        for (i = 0; i < myCanvas.height / squareSize; i++) {
            var j:int;
            for (j = 0; j < myCanvas.width / squareSize; j++) {
                if (Math.random() < 0.5) {
                    square.graphics.beginFill(0x000000, 1.0);
                    square.graphics.drawRect(j * squareSize, i * squareSize, squareSize, squareSize);
                }
            }
        }

        square.graphics.endFill();
        myCanvas.rawChildren.addChild(square);
    }
]]>
</mx:Script>

    <mx:Panel title="Random Squares" height="95%" width="95%" 
        paddingTop="5" paddingLeft="5" paddingRight="5" paddingBottom="5">

        <mx:Canvas id="myCanvas" borderStyle="solid" height="100%" width="100%">
        </mx:Canvas>

    </mx:Panel>
</mx:Application>

1 个答案:

答案 0 :(得分:2)

您在显示列表中添加了无限数量的孩子,因此您肯定会遇到性能问题。

您可以在添加新形状之前删除旧形状

myCanvas.rawChildren.removeChildAt(0);
myCanvas.rawChildren.addChild(square);

你也可以完全取消广场 - 但是在绘制之前请注意Graphics.clear()电话。否则,图形对象将填充数据,就像现在的显示列表一样。

public function draw():void {
    var squareSize:uint = 10;

    myCanvas.graphics.clear();
    myCanvas.graphics.beginFill(0xFFFFFF, 1.0);
    myCanvas.graphics.drawRect(0, 0, myCanvas.width, myCanvas.height);
    ...
        myCanvas.graphics.beginFill(0x000000, 1.0);
        myCanvas.graphics.drawRect(...)
    ...
    myCanvas.graphics.endFill();
}