Java Reference
In-Depth Information
determine whether a shape contains a point or a rectangle; a Shape has to be able
to tell its inside from its outside. Because our spiral is a curve that doesn't enclose
an area, there is no inside, and these methods always return false. The inter-
sects() methods determine whether any part of the shape intersects a specified
rectangle. Since this is hard to compute exactly for a spiral, the code approximates
the spiral with a circle for the purposes of these methods.
The getPathIterator() methods are the heart of any Shape implementation. Each
method returns a PathIterator object that describes the outline of the shape in
terms of line and curve segments. Java 2D relies on PathIterator objects to draw
and fill shapes. The key methods of the SpiralIterator implementation are cur-
rentSegment() , which returns one line segment of the spiral, and next() , which
moves the iterator to the next segment. next() uses some hairy mathematics to
make sure that the line segment approximation of the spiral is good enough.
Example 11•14: Spiral.java
package com.davidflanagan.examples.graphics;
import java.awt.*;
import java.awt.geom.*;
/** This Shape implementation represents a spiral curve */
public class Spiral implements Shape {
double centerX, centerY;
// The center of the spiral
double startRadius, startAngle;
// The spiral starting point
double endRadius, endAngle;
// The spiral ending point
double outerRadius;
// the bigger of the two radii
int angleDirection;
// 1 if angle increases, -1 otherwise
/**
* The constructor. It takes arguments for the center of the shape, the
* start point, and the end point. The start and end points are specified
* in terms of angle and radius. The spiral curve is formed by varying
* the angle and radius smoothly between the two end points.
**/
public Spiral(double centerX, double centerY,
double startRadius, double startAngle,
double endRadius, double endAngle)
{
// Save the parameters that describe the spiral
this.centerX = centerX; this.centerY = centerY;
this.startRadius = startRadius; this.startAngle = startAngle;
this.endRadius = endRadius;
this.endAngle = endAngle;
// figure out the maximum radius, and the spiral direction
this.outerRadius = Math.max(startRadius, endRadius);
if (startAngle < endAngle) angleDirection = 1;
else angleDirection = -1;
if ((startRadius < 0) || (endRadius < 0))
throw new IllegalArgumentException("Spiral radii must be >= 0");
}
/**
* The bounding box of a Spiral is the same as the bounding box of a
* circle with the same center and the maximum radius
**/
public Rectangle getBounds() {
Search WWH ::




Custom Search