getNestedBounds: A getBounds Replacement for Complex Display Objects [AS3] · Oct 9, 06:23 PM

Is the built-in getBounds function not quite living up to your needs? When calculating bounds on objects without children, getBounds works exactly as you might expect. However, once child objects are added to the mix the results you get may seem unexpected and loose. The solution is to recursively calculate bounds on all the child objects. I give you getNestedBounds() which can be used as a replacement for any getBounds() statement

  1. /**
  2. * A Smart version of DisplayObjectContainer's builtin function, ie: target.getBounds(targetCoordinateSpace)
  3. * When objects are nested, this function will produce a tighter result than DisplayObjectContainer.getBounds()
  4. * Note: This function works on any DisplayObject, even if there are no nested children
  5. * Note: Empty child DisplayObjects are essentially ignored
  6. * param: target: see Sprite.getBounds()
  7. * param: targetCoordinateSpace: see Sprite.getBounds()
  8. * return: Rectangle bounds
  9. */
  10. public static function getNestedBounds(target:DisplayObject, targetCoordinateSpace:DisplayObject):Rectangle {
  11. if (target.hasOwnProperty("numChildren") && (target as DisplayObjectContainer).numChildren > 0) {
  12. var j:int = 1;
  13. var nbounds:Rectangle = getNestedBounds((target as DisplayObjectContainer).getChildAt(0), targetCoordinateSpace);
  14. while ((nbounds.width == 0 || nbounds.height == 0) && j < (target as DisplayObjectContainer).numChildren) {
  15. nbounds = getNestedBounds((target as DisplayObjectContainer).getChildAt(j), targetCoordinateSpace);
  16. j++;
  17. }
  18. for (var i:int = j; i < (target as DisplayObjectContainer).numChildren; i++ ) {
  19. var bounds:Rectangle = getNestedBounds((target as DisplayObjectContainer).getChildAt(i), targetCoordinateSpace);
  20. if (bounds.width > 0 && bounds.height > 0) {
  21. var x0:Number = Math.min(bounds.x, nbounds.x);
  22. var y0:Number = Math.min(bounds.y, nbounds.y);
  23. var x1:Number = Math.max(bounds.x + bounds.width, nbounds.x + nbounds.width);
  24. var y1:Number = Math.max(bounds.y + bounds.height, nbounds.y + nbounds.height);
  25. nbounds.x = x0;
  26. nbounds.y = y0;
  27. nbounds.width = x1 - x0;
  28. nbounds.height = y1 - y0;
  29. }
  30. }
  31. return nbounds;
  32. } else {
  33. return target.getBounds(targetCoordinateSpace);
  34. }
  35. }
  36. Download this code: /files/getNestedBounds.txt

When might you find such a thing useful? Mainly, when you need to rasterize complex display objects into a single Bitmap, or save an image to your server

— Pickle

---

Comment

Textile Help