7.2. Getting Close to the Metal

The 2D API gives you absolute control over glyphs and their layout, if you want it. The text rendering methods I've described so far all take advantage of automatic layout mechanisms. You pass a string to drawString() or to a TextLayout and the 2D API worries about the details of laying out the glyphs. For total control, you can manipulate the shapes yourself.

Why would you want to do this? It's possible you won't be satisfied with the way TextLayout or drawString() is formatting your text and you'd rather use your own layout algorithm. Another possibility is that you may want to achieve funky text effects, like text with a curved baseline. You need glyph-level control for that kind of effect.

There are two classes that relate directly to glyphs. The java.awt.font.GlyphVector class represents a set of glyphs, each with its own position. The java.awt.font.GlyphMetrics class encapsulates measurements for a single glyph.

To actually render glyphs individually, you can retrieve them from a GlyphVector as a Shape and pass them to Graphics2D's fill() or draw() methods, as for any other shape. Graphics2D also has a method for drawing an entire GlyphVector:

public abstract void drawGlyphVector(GlyphVector g, float x, float y)

This method renders the glyphs contained in the supplied GlyphVector, using x and y as the baseline location.

7.2.1. Creating GlyphVectors

A GlyphVector holds only glyphs from a single font. If you are trying to render styled ...

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.