如何在 Flash/AS3 中定义可见 children 的矩形("real" 元素大小)

How to define rectangle of visible children in Flash/AS3 ("real" element size)

我使用 BitmapData.draw 制作了一张图 canvas 的快照。在 canvas 上,随机位置(包括负数位置)有一些 children。我应该以某种方式定义要拍摄的矩形范围。

所以,例如,我在视图中有 3 个节点 (canvas):

在这种情况下,边界应该是 (-5; -3)(左上)到 (70; 70)(右下)。

有没有办法根据 children 布局定义 "real" 元素大小?

可能是来自 Flex 框架的一些方法?

DisplayObject.getBounds() and DisplayObject.getRect() 是您正在寻找的方法。

两种方法

[Return] a rectangle that defines the boundary of the display object, based on the coordinate system defined by the targetCoordinateSpace parameter

它们的区别是:

The getBounds() method is similar to the getRect() method; however, the Rectangle returned by the getBounds() method includes any strokes on shapes, whereas the Rectangle returned by the getRect() method does not.

如果你使用笔画,你可能想使用getBounds()

看起来在大多数情况下 getBounds()getRect() 应该可以工作,但有时它们在计算 right-bottom 角时可能会出现问题,例如,当组件显式调整大小时。

对于我的组件,我发现已经实现了方法(这个解决方案也忽略了不可见的 children!):

public function calcDisplayObjecBoundingBox():Rectangle
  {
    var numChildren:int = this.numChildren;

    var result:Rectangle = new Rectangle( 0, 0, 0, 0 );
    var i:int = 0;
    var child:DisplayObject;

    if( numChildren > 0 )
    {

      //find first visible child and initialize rectangle bounds
      for( i = 0; i < numChildren; i++ )
      {
        child = this.getChildAt( i );

        if( child.visible )
        {
          result.left = child.x;
          result.top = child.y;
          result.right = child.x + child.width;
          result.bottom = child.y + child.height;
          i++;
          break;
        }
      }

      for( ; i < numChildren; i++ )
      {
        child = this.getChildAt( i );

        if( child.visible )
        {
          result.left = Math.min( result.left, child.x );
          result.right = Math.max( result.right, child.x + child.width );
          result.top = Math.min( result.top, child.y )
          result.bottom = Math.max( result.bottom, child.y + child.height );
        }
      }
    }

可能,它的工作原理与 getBounds()getRect() 几乎相同,但通过 children 计算 right-bottom 点,而不是组件本身。