2007年5月24日星期四

getBounds() vs getRect()

Like ActionScript 1 and 2, ActionScript 3 has a getBounds() (flash.display.DisplayObject.getBounds()) method for determining the bounds of a movie clip (display object) in the coordinate space of any timeline. In ActionScript 3, however, getBounds has changed to return a Rectangle (flash.geom.Rectangle) instance instead of a generic object with the properties xMin, xMax, yMin, and yMax.

ActionScript 3 also adds an additional method similar to getBounds called getRect() (flash.display.DisplayObject.getRect()). The getRect() method works just like getBounds except it doesn't take into consideration strokes on shapes.

The following example shows the differences between the rectangle shape returned by getBounds and that returned by getRect.

ActionScript Code:

var sprite:Sprite = new Sprite();
sprite.
graphics.beginFill(0x999999);
sprite.
graphics.lineStyle(10, 0x333);
sprite.
graphics.drawCircle(100, 100, 50);
sprite.
graphics.endFill();
addChild(sprite);

addChild(createRectShape(sprite.
getRect(this), 0xFF00FF));
addChild(createRectShape(sprite.
getBounds(this), 0xFF0000));

function createRectShape(rect:Rectangle,
color:uint):Shape {
var rectShape:Shape = new Shape();
rectShape.
graphics.lineStyle(0, color);
rectShape.
graphics.drawRect(rect.left, rect.top, rect.width, rect.height);
return rectShape;
}



Running the above script draws a circle with a stroke of 10 px with two rectangles around it, one which fits to the vector shape of the circle (getRect) and the other which fits to the bounds of the whole object including the stroke (getBounds).

The rectangle returned by getRect relates to width and height values associated with the display object (which doesn't account for strokes) while getBounds returns a rectangle associated with the visual boundaries of the display object. Note that filters are not accounted for in either method.

1评论:

Typhone 说...

看了一下代碼的效果,有點困惑
getRect似乎有點多余,不喜歡相交效果

如果getRect返回內切框,getBounds返回外切框就好了

!:)