Java Reference
In-Depth Information
A Rectangle2D object has getX() and getY() methods for retrieving the coordinates of the top-left
corner, and getWidth() and getHeight() methods that return the width and height of the rectangle, re-
spectively.
A round rectangle is a rectangle with rounded corners. The corners are defined by a width and a height
and are essentially a quarter segment of an ellipse (I get to the details of ellipses later). Of course, if the
corner width and height are equal, then the corner is a quarter of a circle.
You can define a round rectangle using coordinates of type double with the following statements:
Point2D.Double position = new Point2D.Double(10, 10);
double width = 200.0;
double height = 100;
double cornerWidth = 15.0;
double cornerHeight = 10.0;
RoundRectangle2D.Double roundRect = new RoundRectangle2D.Double(
position.x, position.y, // Position
of top-left
width, height, // Rectangle
width & height
cornerWidth, cornerHeight); // Corner
width & height
The only difference between this and defining an ordinary rectangle is the addition of the width and
height to be applied for the corner rounding.
Combining Rectangles
You can combine two rectangles to produce a new rectangle that is either the union of the two original rect-
angles or the intersection. The union of two rectangles is the smallest rectangle enclosing both. The inter-
section is the rectangle that is common to both. Let's take a couple of specifics to see how this works. You
can create two rectangles with the following statements:
float width = 120.0f;
float height = 90.0f;
Rectangle2D.Float rect1 = new Rectangle2D.Float(50.0f, 150.0f, width, height);
Rectangle2D.Float rect2 = new Rectangle2D.Float(80.0f, 180.0f, width, height);
You can obtain the intersection of the two rectangles with the following statement:
Rectangle2D.Float rect3 = rect1.createIntersection(rect2);
The effect is illustrated in Figure 19-8 by the shaded rectangle. Of course, the result is the same if you
call the method for rect2 with rect1 as the argument. If the rectangles don't overlap, the rectangle that is
returned is the rectangle from the bottom right of one rectangle to the top right of the other that does not
overlap either of the original rectangles.
FIGURE 19-8
 
 
Search WWH ::




Custom Search