A Quick Tour of Java 2D
Filling Shapes
The
simplest path through the rendering pipeline is for
filling
shapes. For example, the following code creates an ellipse and fills
it with a solid color. (This code would live inside a paint( ) method somewhere. We’ll present a complete,
ready-to-run example a little later.)
Shape c = new Ellipse2D.Float(50, 25, 150, 150); g2.setPaint(Color.blue); g2.fill(c);
The Ellipse2D
class is abstract, but is implemented by
concrete inner subclasses, called
Float
and Double. The
Rectangle2D
class, for example, has concrete
subclasses Rectangle2D.Float and
Rectangle2D.Double.
In the call to setPaint( ), we tell the
Graphics2D to use a solid color, blue, for all
subsequent filling operations. Then, the call to fill( ) tells Graphics2D to fill the given
shape.
All geometric shapes in the 2D API are represented by implementations
of the
java.awt.geom.Shape
interface. This
interface defines methods that are common to all shapes, like
returning a rectangle bounding box or testing if a point is inside
the shape. The
java.awt.geom
package is a smorgasbord of useful
shape classes, including
Rectangle2D, RoundRectangle2D
(a rectangle with rounded corners), Arc2D,
Ellipse2D, and others. In addition, a few classes
in java.awt are Shapes:
Rectangle, Polygon, and
Area.
Drawing Shape Outlines
Drawing a shape’s outline is only a little bit more complicated. Consider this example:
Shape r = new Rectangle2D.Float(100, 75, 100, 100); g2.setStroke(new BasicStroke(4)); ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access