Java Reference
In-Depth Information
Example 11•6: Shapes.java (continued)
for(int i = 0; i < 10; i++)
p.addPoint((int)(100*Math.random()), (int)(100*Math.random()));
shapes[10] = p;
}
// These are the labels for each of the shapes
String[] labels = new String[] {
"Line2D", "QuadCurve2D", "CubicCurve2D", "Arc2D (OPEN)",
"Arc2D (CHORD)", "Arc2D (PIE)", "Ellipse2D", "Rectangle2D",
"RoundRectangle2D", "Polygon", "Polygon (random)", "Spiral"
};
/** Draw the example */
public void draw(Graphics2D g, Component c) {
// Set basic drawing attributes
g.setFont(new Font("SansSerif", Font.PLAIN, 10)); // select font
g.setStroke(new BasicStroke(2.0f)); // 2 pixel lines
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // antialiasing
RenderingHints.VALUE_ANTIALIAS_ON);
g.translate(10, 10);
// margins
// Loop through each shape
for(int i = 0; i < shapes.length; i++) {
g.setColor(Color.yellow); // Set a color
g.fill(shapes[i]); // Fill the shape with it
g.setColor(Color.black); // Switch to black
g.draw(shapes[i]); // Outline the shape with it
g.drawString(labels[i], 0, 110); // Label the shape
g.translate(120, 0); // Move over for next shape
if (i % 6 == 5) g.translate(-6*120, 120); // Move down after 6
}
}
}
Transforms
The AffineTransform class can transform a shape (or coordinate system) by trans-
lating, scaling, rotating, or shearing it, using any combination of these individual
transformation types. Figure 11-5 illustrates the results of various types of coordi-
nate-system transformations on the appearance of one shape, drawn multiple
times. Example 11-7 shows the Java code that generates the figure.
An afÞne transfor mation is a linear transformation that has two important proper-
ties: all straight lines remain straight, and all parallel lines remain parallel. The
AffineTransform class can perform a great variety of transformations, but it can't
produce nonlinear effects, such as distorting a figure as through a fisheye lens.
That kind of effect can be achieved only with image-processing techniques. For a
further discussion of transformations and of the linear algebra behind the Affine-
Transform class, see Chapter 4 of Java Foundation Classes in a Nutshell .
Example 11•7: Transforms.java
package com.davidflanagan.examples.graphics;
import java.awt.*;
import java.awt.geom.*;
Search WWH ::




Custom Search