簡體   English   中英

在Flex畫布上繪制正方形

[英]Drawing squares on Flex Canvas

我正在嘗試向Flex畫布上的正方形動畫圖像編寫一些代碼。 下面的代碼有問題,因為它的速度越來越慢。 我認為我應該清除舊的方塊或其他東西。

我在下面做什么錯了:

<?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>

您要將無限數量的子代添加到顯示列表中,因此肯定會遇到性能問題。

您可以先刪除舊形狀,然后再添加新形狀

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM