Skip to main content

Glyphs and shaping

draw_text hands you pixels. The glyph level hands you the pieces it is made from, so you can draw text at any size, angle or shear, filled or stroked, through a matrix, or send it to another renderer. Everything here is in font units, the font's own design grid, with y pointing up. To get pixels, multiply by size / (ascent - descent), which is the scale draw_text uses for its pixel height.

import os

import libstb as stb

os.makedirs("out", exist_ok=True)
font = stb.Font.open("Vazirmatn-Regular.ttf")

# The font's own grid, and what it holds.
d = font.design_metrics
print("units per em:", d.units_per_em)
print("glyphs:", font.glyph_count, "faces:", stb.Font.face_count("Vazirmatn-Regular.ttf"))

# A character is a glyph index (0 is "no glyph"). Metrics and outlines are in font units, with y pointing up.
a, v = font.glyph_index("A"), font.glyph_index("V")
print("A is glyph", a, "with advance", round(font.glyph_info(a).advance))
print("outline of A:", len(font.outline(a)), "commands")
for mode in ("none", "kern_table", "automatic"):
print(f"kerning of A and V ({mode}):", round(font.glyph_kerning(a, v, mode)))

# Shaping decides which glyphs a text becomes, in visual order, left to right on the page.
print("shape AV:", len(font.shape("AV")), "glyphs")
persian = "سلام دنیا"
shaped = font.shape(persian)
print("shape Persian:", len(shaped), "glyphs, the first from byte", shaped[0].cluster)


def draw_text(img, text, size, x, baseline, color, angle=0.0):
"""Draws `text` as vector outlines; the first pen position is (x, baseline). `angle` is in radians, clockwise."""
d = font.design_metrics
scale = size / (d.ascent - d.descent) # font units to pixels
pitch = (d.ascent - d.descent + d.line_gap) * scale # from one baseline to the next
pen, line = 0.0, 0
for g in font.shape(text):
if g.glyph == 0: # a line break
line, pen = line + 1, 0.0
continue
# Each call applies to a point first: scale and flip y, place the glyph on the line, turn the line, put it on the image.
m = (
stb.Matrix()
.translate(x, baseline)
.rotate(angle)
.translate((pen + g.x_offset) * scale, line * pitch - g.y_offset * scale)
.scale(scale, -scale)
)
img = img.fill_outline(stb.Outline(font.outline(g.glyph)), color, matrix=m)
pen += g.x_advance
return img


img = stb.Image.open("astronaut.png").crop(0, 0, 512, 300).fill((245, 243, 238))
img = draw_text(img, "Hello, AV kerning", 44, 20, 60, "#1e1e1e")
img = draw_text(img, persian, 44, 20, 120, "#1d3557")
img = draw_text(img, "one\ntwo lines", 30, 20, 175, "#e63946")
img = draw_text(img, "tilted text", 40, 230, 270, "#2a9d8f", angle=-0.35)
img.write("out/vector_text.png")
Output
units per em: 2048
glyphs: 1333 faces: 1
A is glyph 2 with advance 1336
outline of A: 15 commands
kerning of A and V (none): 0
kerning of A and V (kern_table): 0
kerning of A and V (automatic): -87
shape AV: 2 glyphs
shape Persian: 8 glyphs, the first from byte 15
out/vector_text.png
out/vector_text.png

The pieces​

  • Design metrics: units_per_em, ascent, descent and line gap of the font, in font units.
  • Glyph index: a character is looked up in the font's character map and becomes a number. Glyph 0 is the font's "no glyph" shape, used when it has none for a character.
  • Glyph info and outline: the advance and the ink box of a glyph, and its outline as move, line, quadratic and cubic commands, which you can wrap in an Outline and fill or stroke like any other vector outline.
  • Kerning between two glyphs, from the kern table, from the GPOS table, or none. The automatic mode uses GPOS when the font has it and the kern table otherwise, which is what draw_text does.

Shaping​

Shaping decides which glyphs a text becomes: joining forms, ligatures, marks placed on letters, kerning, and the order for the eye. shape returns the glyphs in visual order, left to right on the page, each with its advance and offsets, and a cluster that says which byte of the text it came from. For Persian the clusters run backwards, which is how you see that the line is right to left. A glyph index of 0 in the result is a line break.

A renderer of your own​

The function in the example shapes the text, then draws each glyph's outline through a matrix. Each call on the matrix applies to a point first, so read the chain from the bottom up: scale the glyph and flip y (font units go up, pixels go down), move it to its place on the line, turn the line by the angle, put the line on the image. Changing the angle, adding a shear or stroking the outline instead of filling it is one more call in that chain.

API at a glance​

Design metricsfont.design_metrics
Glyph of a characterfont.glyph_index("A")
Glyph metricsfont.glyph_info(g)
Outlinefont.outline(g), wrap in stb.Outline(...)
Kerningfont.glyph_kerning(a, b, "automatic")
Shape a textfont.shape(text)
Faces in a filestb.Font.face_count(path)