CONTENTS | PREV | NEXT Java 2D API


2.8 Compositing Images

A Graphics2D context includes a Composite object that encapsulates the composition style to use if objects overlap. AlphaComposite implements a number of common composition rules that support blending and transparency effects. The most commonly used is SRC_OVER.


2.8.1 Using the Source Over Composition Rule

The SRC_OVER composition rule composites the source pixel over the destination pixel so that the shared pixel takes the color of the source pixel. For example, if you render a blue rectangle and then render a red rectangle that partially overlaps it, the overlapping area will be red. In other words, the object that is rendered last will appear to be on top.

To use the SRC_OVER composition rule:

  1. Create an AlphaComposite object by calling getInstance and specifying the SRC_OVER rule.
AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER);
  1. Call setComposite to add the AlphaComposite object to the Graphics2D context.
g2.setComposite(ac);
Once the composite object is set, overlapping objects will be rendered using the specified composition rule.


2.8.2 Increasing the Transparency of Composited Objects

AlphaComposite allows you to specify an additional constant alpha value that is multiplied with the alpha of the source pixels to increase transparency.

For example, to create an AlphaComposite object that renders the source object 50% transparent, specify an alpha of .5:

AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f);
In the following example, a source over alpha composite object is created with an alpha of .5 and added to the graphics context, causing subsequent shapes to be rendered 50% transparent.

public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.red);
g2.translate(100,50);
// radians=degree * pie / 180
g2.rotate((45*java.lang.Math.PI)/180);
g2.fillRect(0,0,100,100);
g2.setTransform(new AffineTransform()); // set to identity
// Create a new alpha composite
AlphaComposite ac =
AlphaComposite.getInstance(AlphaComposite.SRC_OVER,0.5f);
g2.setComposite(ac);
g2.setColor(Color.green);
g2.fillRect(50,0,100,100);
g2.setColor(Color.blue);
g2.fillRect(125,75,100,100);
g2.setColor(Color.yellow);
g2.fillRect(50,125,100,100);
g2.setColor(Color.pink);
g2.fillRect(-25,75,100,100);
}


CONTENTS | PREV | NEXT
Copyright © 1997-1998 Sun Microsystems, Inc. All Rights Reserved.