User Guide
422 Working with Geometry
Finding unions and intersections of Rectangle
objects
You use the union() method to find the rectangular region formed by the boundaries of two
rectangles:
import flash.display.*;
import flash.geom.Rectangle;
var rect1:Rectangle = new Rectangle(0, 0, 100, 100);
trace(rect1); // (x=0, y=0, w=100, h=100)
var rect2:Rectangle = new Rectangle(120, 60, 100, 100);
trace(rect2); // (x=120, y=60, w=100, h=100)
trace(rect1.union(rect2)); // (x=0, y=0, w=220, h=160)
You use the intersection() method to find the rectangular region formed by the
overlapping region of two rectangles:
import flash.display.*;
import flash.geom.Rectangle;
var rect1:Rectangle = new Rectangle(0, 0, 100, 100);
trace(rect1); // (x=0, y=0, w=100, h=100)
var rect2:Rectangle = new Rectangle(80, 60, 100, 100);
trace(rect2); // (x=120, y=60, w=100, h=100)
trace(rect1.intersection(rect2)); // (x=80, y=60, w=20, h=40)
You use the intersects() method to find out whether two rectangles intersect. You can also
use the
intersects() method to find out whether a display object is in a certain region of
the Stage. For example, in the following code, assume that the coordinate space of the display
object container that contains the
circle object is the same as that of the Stage. The example
shows how to use the
intersects() method to determine if a display object, circle,
intersects specified regions of the Stage, defined by the
target1 and target2 Rectangle
objects:
import flash.display.*;
import flash.geom.Rectangle;
var circle:Shape = new Shape();
circle.graphics.lineStyle(2, 0xFF0000);
circle.graphics.drawCircle(250, 250, 100);
addChild(circle);
var circleBounds:Rectangle = circle.getBounds(stage);
var target1:Rectangle = new Rectangle(0, 0, 100, 100);
trace(circleBounds.intersects(target1)); // false
var target2:Rectangle = new Rectangle(0, 0, 300, 300);
trace(circleBounds.intersects(target2)); // true
Similarly, you can use the intersects() method to find out whether the bounding
rectangles of two display objects overlap. You can use the
getRect() method of the
DisplayObject class to include any additional space that the strokes of a display object may
add to a bounding region.