Getting Visible Bounds in Actionscript 3.0


By daniel - Posted on 20 October 2008

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