6.4. Font Metrics

Before the 2D API, the java.awt.FontMetrics class provided font measurement information. In the old system, you would pass a Font to Toolkit's getFontMetrics() method. In the 2D API, FontMetrics still exists and is not deprecated; nevertheless, it has been replaced with the java.awt.font.LineMetrics class. Unless you have to work with old versions of the JDK, I suggest ignoring FontMetrics entirely.

In the new scheme, you can ask a Font for a LineMetrics object by calling one of its getLineMetrics() methods. Essentially, these methods accept a string and return a LineMetrics object that encapsulates the dimensions of the rendered string.

6.4.1. The FontRenderContext Class

Measuring text is a delicate operation. When the rendering engine (a Graphics2D) renders text, the results depend on the engine's rendering hints. In particular, the value of the KEY_ANTIALIASING hint and the KEY_FRACTIONAL-METRICS hints make subtle changes in the dimensions of rendered text. (For more information on rendering hints, see Chapter 5.)

The bottom line is that you need to specify whether antialiasing and fractional metrics will be used when you ask for a LineMetrics object. This information is contained in a java.awt.font.FontRenderContext object. This class has one public constructor:

public FontRenderContext(AffineTransform tx, boolean isAntiAliased, boolean usesFractionalMetrics)

Use this constructor to create a FontRenderContext. The transformation that will be used to convert ...

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.