Friday, December 12, 2008

ActionScript3 DisplayListUtils


-- Warning: Most readers will find this post extremely geeky. There is entertaining posts below I swear.

So half of my waking day is spent writing code. It's something I don't share much with others, but I realized that's stupid. The Internet helps ensure nobody has to reinvent wheels.

So here's something for everyone drawing graphics with ActionScript3. It's a class of static methods that are a huge help when goofing around with the display list. Especially handy is the removeChildren method which should already exist in the DisplayObjectContainer class but for some reason doesn't. I use it all the time.

Enjoy, my potential Internet friends.


package utils {

import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.geom.Rectangle;

public class DisplayListUtils {

public static function traceDisplayObject( container:DisplayObjectContainer, indentString:String ="" ):void {
var child:DisplayObject;
for ( var i:uint=0; i < container.numChildren; i++ ) {
child = container.getChildAt(i);
trace( indentString, child, child.name, 'visible = '+child.visible );
if ( container.getChildAt(i) is DisplayObjectContainer ) {
traceDisplayObject( DisplayObjectContainer( child ), indentString + " ")
}
}
}

public static function highlightBounds( d:DisplayObject, c:DisplayObjectContainer ):void {
var cs:Sprite = Sprite( c );
d.getBounds( c );
var r:Rectangle = d.getBounds( c );
cs.graphics.beginFill( 0xFF0000, .25 );
cs.graphics.drawRect( r.x, r.y, r.width, r.height );
cs.graphics.endFill();
}

public static function traceBounds( d:DisplayObject, c:DisplayObjectContainer ):void {
var cs:Sprite = Sprite( c );
d.getBounds( c );
var r:Rectangle = d.getBounds( c );
cs.graphics.lineStyle( 2, 0x000000, 1 );
cs.graphics.beginFill( 0x000000, .5 );
cs.graphics.drawRect( r.x, r.y, r.width, r.height );
cs.graphics.endFill();
}

public static function highlightAll( c:DisplayObjectContainer, depth:int=-1 ):void {
for ( var i:uint=0; i < c.numChildren; i++ ) {
traceBounds( c.getChildAt(i), c );
if ( i == depth ) {
return
}
else if ( c.getChildAt(i) is DisplayObjectContainer ) {
highlightAll( DisplayObjectContainer( c.getChildAt(i) ), depth );
}
}
}

public static function drawDisplayObjectArea( c:DisplayObjectContainer ):void {
var cs:Sprite = Sprite( c );
cs.graphics.clear();
for ( var i:int = c.numChildren-1; i > -1; i-- ) {
var d:DisplayObject = c.getChildAt( i );
var r:Rectangle = d.getBounds( c );
cs.graphics.beginFill( 0xFF0000, .25 );
cs.graphics.drawRect( r.x, r.y, r.width, r.height );
cs.graphics.endFill();
}
}

public static function removeChildren( c:DisplayObjectContainer ):void {
for ( var i:int = c.numChildren-1; i > -1; i-- ) {
c.removeChildAt( i );
}
}
}
}

No comments: