2009-12-23 4 views
0

J'essaie d'écrire du code sur des images animées de carrés sur une toile Flex. Il y a un problème avec mon code ci-dessous car il devient progressivement plus lent. Je suppose que je suis censé effacer les vieux carrés ou quelque chose.Dessiner des carrés sur Flex Canvas

Qu'est-ce que je fais mal ?: ci-dessous

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

Répondre

2

Vous ajoutez un nombre indéfini d'enfants à votre liste d'affichage, vous êtes certainement en difficulté de la performance.

Vous pouvez supprimer les anciennes formes avant d'ajouter le nouveau

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

Vous pouvez également faire disparaître la place entièrement - noter l'appel Graphics.clear() avant de tirer, cependant. Sinon, l'objet graphique se remplira de données comme la liste d'affichage est maintenant.

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

Merci! Ça a marché. Il y avait juste une petite faute de frappe dans votre deuxième solution. Cette ligne: square.graphics.drawRect (0, 0, myCanvas.width, myCanvas.height); doit être: myCanvas.graphics.drawRect (0, 0, myCanvas.width, myCanvas.height); –

Questions connexes