5.2. Compositing

Compositing is the process of putting two pictures together. In the 2D API, compositing occurs every time you draw a shape or an image. As I explained in Chapter 2, an instance of Graphics2D represents a drawing surface. Each time you draw a shape, some text, or an image, the new element is added to the drawing surface. Conceptually, it happens in distinct steps:

  1. The rasterizer takes the ideal shape and produces a set of alpha values from it. You can think of this as a grid of pixels, where each pixel has an alpha value. Essentially, this is an image as large as the drawing surface. I'll call this new image the source ; the drawing surface is the destination.

  2. The colors in the source are determined, using either the current Paint of the Graphics2D or the colors of an image.

  3. The source and the destination are combined to form the new destination (drawing surface). This is done at the pixel level. The color and alpha of each pixel is determined by combining the colors and alpha values from the corresponding pixels in the source and destination. A compositing rule specifies exactly how the color and alpha values are used.

For example, consider what happens when a black shape is rendered on a white canvas using the default source over destination compositing rule. The rasterizer converts the ideal shape to an array of alpha values. Source pixels that lie entirely outside the shape have an alpha of 0.0. This is interpreted as complete transparency; for these pixels, ...

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.