Displaying Graphics with Graphics2D |
TheAlphaComposite
class encapsulates different compositing styles, which determine how overlapping objects are rendered. AnAlphaComposite
can also have an alpha value that specifies the degree of transparency: alpha=1.0 is totally opaque, alpha=0.0 is totally transparent (clear).AlphaComposite
supports the standard Porter-Duff compositing rules:To change the compositing style used by
Graphics2D
, you create anAlphaComposite
object and pass it into thesetComposite
method.Example: Composite
The
A newComposite
program illustrates the effects of different compositing style and alpha combinations.AlphaComposite
object ac is constructed callingAlphaComposite
.getInstance
and specifying the desired compositing rule.When a different compositing rule or alpha value is selected,AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC);AlphaComposite
.getInstance
is called again and the newAlphaComposite
is assigned to ac . The selected alpha is passed as a second parameter toAlphaComposite
.getInstance
:ac = AlphaComposite.getInstance(getRule(rule), alpha);The composite attribute is modified by passing the
AlphaComposite
object toGraphics 2D
setComposite
. The objects are rendered into aBufferedImage
and later copied to the screen, so the composite attribute is set on theGraphics2D
context for theBufferedImage
:BufferedImage buffImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D gbi = buffImg.createGraphics(); ... gbi.setComposite(ac);You can find the complete code for this program in
Composite.java
and an HTML file that includes the applet inComposite.html
.
Displaying Graphics with Graphics2D