Java Reference
In-Depth Information
Example 11•14: Spiral.java (continued)
/** This method is the same as above, except using double values */
public int currentSegment(double[] coords) {
coords[0] = centerX + radius*Math.cos(angle);
coords[1] = centerY - radius*Math.sin(angle);
if (transform != null) transform.transform(coords, 0, coords, 0,1);
if (angle == endAngle) done = true;
if (angle == startAngle) return SEG_MOVETO;
else return SEG_LINETO;
}
/**
* Move on to the next segment of the path. Compute the angle and
* radius values for the next point in the spiral.
**/
public void next() {
if (done) return;
// First, figure out how much to increment the angle. This
// depends on the required flatness, and also upon the current
// radius. When drawing a circle (which we'll use as our
// approximation) of radius r, we can maintain a flatness f by
// using angular increments given by this formula:
// a = acos(2*(f/r)*(f/r) - 4*(f/r) + 1)
// Use this formula to figure out how much we can increment the
// angle for the next segment. Note that the formula does not
// work well for very small radii, so we special case those.
double x = flatness/radius;
if (Double.isNaN(x) || (x > .1))
angle += Math.PI/4*angleDirection;
else {
double y = 2*x*x - 4*x + 1;
angle += Math.acos(y)*angleDirection;
}
// Check whether we've gone past the end of the spiral
if ((angle-endAngle)*angleDirection > 0) angle = endAngle;
// Now that we know the new angle, we can use interpolation to
// figure out what the corresponding radius is.
double fractionComplete = (angle-startAngle)/(endAngle-startAngle);
radius = startRadius + (endRadius-startRadius)*fractionComplete;
}
}
}
Custom Strokes
As we saw in Example 11-9, the Stroke class converts a line-drawing operation
into an area-filling operation by taking the Shape whose outline is to be drawn
and returning a stroked shape that represents the outline itself. Because Stroke is
such a simple interface, it is relatively easy to implement custom Stroke classes
that perform interesting graphical effects. Example 11-15 includes four custom
Stroke implementations that it uses along with a simple BasicStroke object to
produce the output shown in Figure 11-12.
Search WWH ::




Custom Search