Java Reference
In-Depth Information
Java2D offers a wide range of attributes for designating color, including line width, fill
patterns, transparency, and many other features.
Fill Patterns
Fill patterns control how a drawn object will be filled in. With Java2D, you can use a
solid color, gradient fill, texture, or pattern of your own devising.
A fill pattern is defined by using the
setPaint(
Paint
)
method of
Graphics2D
with a
Paint
object as its only argument. Any class that can be a fill pattern, including
GradientPaint
,
TexturePaint
, and
Color
, can implement the
Paint
interface. Using a
Color
object with
setPaint()
is the same thing as using a solid color as the pattern.
A
gradient fill
is a gradual shift from one color at one coordinate point to another color
at a different coordinate point. The shift can occur once between the points—which is
called an
acyclic gradient
—or it can happen repeatedly, which is a
cyclic gradient
.
Figure 13.3 shows examples of acyclic and cyclic gradients between white and a darker
color. The arrows indicate the points that the colors shift between.
Acyclic
Cyclic
FIGURE 13.3
Acyclic and cyclic
gradient shifts.
The coordinate points in a gradient do not refer directly to points on the
Graphics2D
object being drawn onto. Instead, they refer to user space and can even be outside the
object being filled with a gradient.
Figure 13.4 illustrates this. Both rectangles are filled using the same
GradientPaint
object as a guide. One way to think of a gradient pattern is as a piece of fabric that has
been spread over a flat surface. The shapes being filled with a gradient are the patterns
cut from the fabric, and more than one pattern can be cut from the same piece of cloth.
13
A call to the
GradientPaint
constructor method takes the following format:
GradientPaint gp = new GradientPaint(
x1, y1, color1, x2, y2, color2);
The point
x1
,
y1
is where the color represented by
color1
begins, and
x2
,
y2
is where
the shift ends at
color2
.