Filling Shapes with Paint
We’ve just seen that line drawing in Java 2D is defined
in terms of the more fundamental operation of area filling. In
previous examples, we’ve used the fill(
)
method of Graphics2D
to
fill the interior of a Shape
with
whatever solid color was previously passed to the setColor( )
method. The Java 2D API
generalizes the notion of color, however, and allows you to fill an
area using any implementation of the Paint
interface. The Paint
implementation is responsible for
specifying the colors to use in the area-filling (or line-drawing)
operation. In Java 1.2 and later, the Color
class implements the Paint
method, allowing shapes to be filled
with solid colors. Java 2D also defines two other Paint
implementations: GradientPaint
, which fills a shape with a
color gradient, and TexturePaint
,
which fills a shape by tiling an image. These classes can be used to
achieve some of the fill effects shown in Figure 12-8.
Figure 12-8. Filling shapes with Paint objects
Example
12-10 shows the code that generates Figure 12-8. In addition to using
the GradientPaint
and TexturePaint
classes, this example
demonstrates a variety of other Java 2D capabilities: translucent
colors, font glyphs as Shape
objects that create “text art,” an AffineTransform
and a translucent color that
produce a shadow effect, and a BufferedImage
that performs off-screen
drawing. Example ...
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.