|
|
Displaying Graphics with Graphics2D |
TheAlphaCompositeclass encapsulates different compositing styles, which determine how overlapping objects are rendered. AnAlphaCompositecan also have an alpha value that specifies the degree of transparency: alpha=1.0 is totally opaque, alpha=0.0 is totally transparent (clear).AlphaCompositesupports the standard Porter-Duff compositing rules:To change the compositing style used by
Graphics2D, you create anAlphaCompositeobject and pass it into thesetCompositemethod.Example: Composite
The
Compositeprogram illustrates the effects of different compositing style and alpha combinations.A newAlphaCompositeobject ac is constructed callingAlphaComposite.getInstanceand specifying the desired compositing rule.When a different compositing rule or alpha value is selected,AlphaComposite ac = AlphaComposite.getInstance(AlphaComposite.SRC);AlphaComposite.getInstanceis called again and the newAlphaCompositeis 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
AlphaCompositeobject toGraphics 2DsetComposite. The objects are rendered into aBufferedImageand later copied to the screen, so the composite attribute is set on theGraphics2Dcontext 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.javaand an HTML file that includes the applet inComposite.html.
![]()
Displaying Graphics with Graphics2D