Getting Visible Bounds in Actionscript 3.0
In Actionscript 3.0 the getBounds() method will include invisible display objects in its calculations. I had a situation where I didn't want this and frankly, was a bit surprised that invisible objects were included in the calculation at all.
I used the code below to define a new method that ignores invisible display objects. Nothing fancy here, it just iterates through the children and, if visible, includes their bounds in the resulting rectangle.
Depending on your needs you can override the existing getBounds() method or, as I did below, define a new method, getVisibleBounds().
public function getVisibleBounds(targetCoordinateSpace:DisplayObject):Rectangle { var bounds:Rectangle = null; for (var i:int = 0; i < this.numChildren; i++) { var child:DisplayObject = this.getChildAt(i); if (child.visible) { if (bounds == null) { bounds = child.getBounds(targetCoordinateSpace); } else { bounds = bounds.union(child.getBounds(targetCoordinateSpace)); } } } if (bounds == null) { return new Rectangle(); } return bounds; }
Delicious
Digg
Reddit
Facebook
Google
Yahoo
Technorati

Comments
This is good start, but not 100%. You're only checking the bounds of the immediate children. What happens if a child IS visible and that child contains it's own children which aren't visible?
You need to run the getVisibleBounds method recursively on ALL children either by having the getVisibleBounds method call itself for every child and child-of-child OR by making sure all DisplayObject's in your application subclass the class you're defining getVisibleBounds in (which would be hard).
You also need to take into account that display objects with masks will return the bounds of the total non-masked area.
I'm not trying to shoot you down. I feel your pain and am also trying to find a solution to this problem. I just wish Adobe would implement a method like this by default.
Hi Will,
You're absolutely right that this will only skip invisible clips if they are immediate children. To have it evaluate all ancestors, it might be easier to use a loop-based depth-first search to iterate through the child DisplayObjects rather than making sure they all define getVisibleBounds via a subclass.
Post new comment