5.3. Clipping

Clipping is a technique that limits the extent of a drawing. The effect is similar to drawing a picture on a sheet of paper and then cutting out part of the picture with scissors. Graphics2D can clip drawings using any Shape. In fact, Graphics2D maintains a clipping shape as part of its state. Figure 5.11 shows a simple drawing in three states: unclipped, clipped to a triangle, and clipped to a circle.

Figure 5.11. Clipping

Graphics2D has methods that manage the current clipping shape, including:

public abstract void clip(Shape s)

This method clips rendering to the specified shape. The intersection of the supplied shape and the current clipping shape becomes the new clipping shape.

public abstract Shape getClip()

Use this method to retrieve the Graphics2D's current clipping shape. This is useful if you want to restore this shape again later.

public abstract void setClip(Shape clip)

This method sets the current clipping shape for this Graphics2D. Unlike clip(), which only modifies the current clipping shape, this method completely replaces it. This is useful for restoring a clipping shape you've previously retrieved with a call to getClip().

There's quite a bit of power here: you can clip rendering using any Shape, including complicated shapes with multiple subpaths. You can even use shapes of text strings for clipping. (Chapter 7, describes how to obtain a Shape ...

Get Java 2D Graphics 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.