Another graphics attribute used by the Graphics2D class is java.awt.RenderingHints. This class is a mapping (a java.util.Map) from a set of rendering hint names to a set of rendering hint values. Unlike with other attributes, Graphics2D defines more than one method to set the rendering hints attribute. setRenderingHints() specifies a new set of hints that replaces the old set of hints, while addRenderingHints() adds a set of hints to the existing set and setRenderingHint() sets the value for a single hint in the current set of hints.
Rendering hints are suggestions to Java 2D about how it should perform its rendering. The RenderingHints class defines a number of constants whose names begin with KEY_. These constants represent the kind of hints you can give. The class also defines a number of constants whose names begin with VALUE_. These are the legal values for the various hints. The names of the VALUE constants make it clear with which hint KEY constant each value is associated.
The purpose of the hints is to allow you to request that Java 2D turn a particular feature, such as antialiasing, on or off. In addition, the hints allow you to suggest what kind of speed versus quality trade-offs Java 2D should make. Remember that these are hints and suggestions to Java 2D, not commands. Not all Java 2D implementations support all the hints, and different implementations have different default values for the hints. Furthermore, the meanings of the hints are not precisely defined, so different implementations may interpret the hints differently.
Suppose that you are writing an application that draws complex graphics. For slow systems, you might want to support a draft mode that draws graphics quickly at the expense of high-quality output. Your code might look like this:
public void paint(Graphics graphics) { Graphics2D g = (Graphics2D)graphics; if (draftmode) { g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_OFF); g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED); g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE); } }
Copyright © 2001 O'Reilly & Associates. All rights reserved.