12 KiB
Fonts
Every font format loads as one Font: metrics, a character map, advances, kerning and glyph images. Outline fonts
(TrueType / OpenType .ttf / .otf / .ttc, WOFF, WOFF2) also give glyph outlines and rasterize at any size.
Bitmap fonts (AngelCode BMFont .fnt) crop their glyphs from page images. Fonts are read-only except BMFont, which is
also how an outline font is baked into a texture atlas for a game.
local font = assert(F.font.load(ttfBytes))
print(font.info.family, font.unitsPerEm) -- DejaVu Sans 2048
local g = font:glyphIndex(string.byte("A")) -- code point -> glyph index (0 = .notdef, missing)
local img = assert(font:rasterize(g, 32)) -- an alpha8 Image, 32 px per em
print(img.width, img.height, img.meta.advance) -- 22 24 21.89
assert(img.format == "alpha8")
The type
Font:
| Field / method | Type | Meaning |
|---|---|---|
kind |
"font" |
|
info |
table | family, style, fullName; outline fonts add the other name table strings (postScriptName, version, copyright, license, ...) |
unitsPerEm |
number | font units per em (TrueType: usually 1000 or 2048; BMFont: the size in pixels) |
ascent, descent, lineGap |
number | font units; descent is negative (below the baseline) |
numGlyphs |
number | glyph indices run 0 .. numGlyphs - 1 |
glyphIndex(self, cp) |
number | the glyph for a Unicode code point, 0 when the font has none |
advance(self, g) |
number | the horizontal advance (font units) |
kern(self, a, b) |
number | the kerning between glyphs a and b (font units, usually negative); 'kern' table and GPOS pairs |
outline(self, g) |
{ cmd }? |
the glyph's outline (outline fonts), nil for a bitmap font or a bad glyph |
rasterize(self, g, px) |
Image? |
the glyph as an alpha8 Image (below) |
pages |
{ Image }? |
BMFont: the page images once loaded |
meta |
table | source.format; outline fonts: outlines ("truetype" / "cff"), tables, os2, italicAngle, underlinePosition, fixedPitch, collection; BMFont: lineHeight, base, pageFiles, bmfont (the parsed descriptor) |
Outline fonts also have font:bounds(g) (xMin, yMin, xMax, yMax in font units, nil for an empty glyph),
font:kernCodepoints(a, b), font:leftSideBearing(g) and font:scale(px) (pixels per font unit, px / unitsPerEm).
Units and directions. Font units are the design grid: multiply by px / unitsPerEm to get pixels for a font
size of px pixels per em. In font units y points up from the baseline. Rasterized images are ordinary images,
rows top to bottom.
Outlines
outline(g) returns a list of commands, each { op = name, x1, y1, ... } with absolute coordinates in font units:
op |
Numbers | Meaning |
|---|---|---|
"moveTo" |
x, y |
start a contour |
"lineTo" |
x, y |
straight line |
"quadTo" |
cx, cy, x, y |
quadratic Bézier (TrueType outlines) |
"cubicTo" |
c1x, c1y, c2x, c2y, x, y |
cubic Bézier (CFF / OpenType outlines) |
"close" |
close the contour |
TrueType fills by the nonzero rule, outer contours clockwise.
local font = assert(F.font.load(ttfBytes))
local cmds = assert(font:outline(font:glyphIndex(string.byte("A"))))
assert(cmds[1].op == "moveTo")
local x0, y0, x1, y1 = font:bounds(font:glyphIndex(string.byte("A")))
assert(y0 == 0 and y1 > 0) -- y up: the A stands on the baseline
local counts = {}
for _, c in cmds do
counts[c.op] = (counts[c.op] or 0) + 1
end
print(counts.moveTo, counts.lineTo, counts.close) -- 2 contours of straight lines
local _ = x0, x1
Rasterized glyphs
rasterize(g, px) renders the glyph antialiased at px pixels per em (the CSS font-size, not the line height).
The result is an alpha8 Image (one coverage byte per pixel, 0 to 255, rows top to bottom), cropped to the ink, with
the placement in meta:
meta field |
Meaning (pixels) |
|---|---|
left |
from the pen position to the image's left edge |
top |
from the baseline up to the image's top row (as FreeType's bitmap_top) |
advance |
how far to move the pen afterwards (fractional) |
glyph |
the glyph index |
Glyphs without ink (the space) give a 0 x 0 image that still has meta.advance. Outline fonts take an optional third
argument { scaleX, scaleY, shiftX, shiftY } (pixels per font unit and a subpixel shift) for stretched or
subpixel-positioned glyphs.
local font = assert(F.font.load(ttfBytes))
local space = assert(font:rasterize(font:glyphIndex(32), 16))
assert(space.width == 0 and space.meta.advance > 0)
assert(font:glyphIndex(0x4E00) == 0) -- no CJK in this font: .notdef
Drawing a string
Place each glyph at the pen position, move the pen by the advance plus the kerning, and draw the coverage onto an
image. F.ops.image.blit converts an alpha8 glyph to white with that alpha and blends it "over" the canvas:
local font = assert(F.font.load(ttfBytes))
local px = 24
local scale = px / font.unitsPerEm
local text = "AVA Hello"
local width = 0
local prev = nil
for _, cp in utf8.codes(text) do -- measure: advances + kerning, in font units
local g = font:glyphIndex(cp)
width += font:advance(g) + (if prev then font:kern(prev, g) else 0)
prev = g
end
local baseline = math.ceil(font.ascent * scale)
local canvas = assert(F.ops.image.new(math.ceil(width * scale) + 2, math.ceil((font.ascent - font.descent) * scale)))
F.ops.image.fill(canvas, 20, 20, 40, 255)
local pen = 1
prev = nil
for _, cp in utf8.codes(text) do
local g = font:glyphIndex(cp)
if prev then
pen += font:kern(prev, g) * scale -- "AV" moves closer
end
local glyph = assert(font:rasterize(g, px))
if glyph.width > 0 then
F.ops.image.blit(canvas, glyph, math.floor(pen + glyph.meta.left + 0.5), baseline - glyph.meta.top)
end
pen += glyph.meta.advance
prev = g
end
assert(font:kern(font:glyphIndex(65), font:glyphIndex(86)) < 0)
local png = assert(F.save(canvas, nil, { format = "png" }))
local _ = png
This is simple left-to-right layout: no shaping (ligatures, Arabic joining, combining marks) and no line breaking.
Load
local ttf = assert(F.font.load(ttfBytes)) -- TrueType
local woff = assert(F.font.load(woffBytes)) -- WOFF 1 (zlib tables)
local woff2 = assert(F.font.load(woff2Bytes)) -- WOFF 2 (Brotli + glyf / loca / hmtx transforms)
assert(woff.info.family == ttf.info.family and woff2.numGlyphs == ttf.numGlyphs)
assert(woff.meta.source.format == "woff" and woff2.meta.source.format == "woff2")
| Option | Format | Meaning |
|---|---|---|
index |
ttf | which font of a collection (.ttc / .otc), 0-based (default 0); F.format("ttf").count gives the count |
pages |
bmfont | the page images, if you have them already (page 0 first) |
loadPage |
bmfont | `function(file, page) -> Image |
BMFont
A BMFont is a descriptor (text, XML or binary .fnt) plus page images that hold the glyphs. The descriptor names the
page files (meta.pageFiles). Metrics are in pixels: unitsPerEm is the size the font was baked at, and
advance, kern, ascent and descent are pixels too. outline returns nil. rasterize(g) crops the glyph from its page
as alpha8 (it ignores px; meta.scale = px / unitsPerEm tells you how much to scale).
The pages load lazily: through opts.loadPage, through opts.pages, through font:loadPages(loader), or, when the
font was loaded from a path, from the files next to the .fnt. Without any of these, rasterize returns nil.
local bm = assert(F.font.load(fntText, {
loadPage = function(file, page)
assert(file == "mini_0.png" and page == 0)
return fntPageBytes -- an Image, or the encoded bytes
end,
}))
assert(bm.meta.source.format == "bmfont" and bm.meta.lineHeight == 9)
local a, b = bm:glyphIndex(65), bm:glyphIndex(66)
assert(bm:advance(a) == 7 and bm:kern(a, b) == -1) -- pixels
local glyph = assert(bm:rasterize(b)) -- loads page 0 now
assert(glyph.format == "alpha8" and glyph.width == 6 and glyph.height == 7)
assert(buffer.readu8(glyph.pixels, 0) == 255) -- the B's outline
local bm = assert(F.font.load(fntText)) -- no loader: the pages are not available yet
assert(bm:rasterize(bm:glyphIndex(65)) == nil)
assert(bm:loadPages(function(file) return F.image.load(fntPageBytes) end))
assert(#bm.pages == 1 and bm:rasterize(bm:glyphIndex(65)))
local bm = assert(F.font.load("assets/mini.fnt")) -- a path: mini_0.png is read from the same folder on demand
assert(bm:rasterize(bm:glyphIndex(65)))
Baking a TTF into a BMFont
F.format("bmfont").bake(font, opts) rasterizes the characters of any outline font and packs them into pages. It
returns a BMFont Font whose pages are rgba8 Images (white, coverage in alpha) and whose meta.pageFiles are
the page file names. Kerning pairs between the baked characters are kept, rounded to pixels.
| Option | Default | Meaning |
|---|---|---|
px |
32 | pixels per em |
chars |
printable ASCII 32..126 | a string, or a list of code points |
pageSize |
smallest power of two that fits (up to 4096) | page width and height |
padding |
1 | empty pixels around each glyph |
file |
"font" |
page file name prefix: pages are <file>_<n>.png |
Save the descriptor with F.save (variant = "text", "xml" or "binary") and each page as a PNG under its
file name:
local ttf = assert(F.font.load(ttfBytes))
local baked = assert(F.format("bmfont").bake(ttf, { px = 16, chars = "Hello, world!", file = "ui" }))
local fnt = assert(F.saveString(baked)) -- the text descriptor (bake gives variant "text")
assert(string.find(fnt, 'page id=0 file="ui_0.png"', 1, true))
local files = { ["ui.fnt"] = fnt }
for i, page in baked.pages do
files[baked.meta.pageFiles[i]] = assert(F.save(page, nil, { format = "png" }))
end
local bin = assert(F.save(baked, nil, { variant = "binary" }))
local again = assert(F.font.load(bin, { pages = baked.pages }))
assert(again:advance(again:glyphIndex(string.byte("H"))) == baked:advance(baked:glyphIndex(string.byte("H"))))
F.save(ttf, dest, { format = "bmfont", px = 16, chars = ... }) bakes too, and writes the page PNGs next to the
.fnt, named after it (ui.fnt gets ui_0.png, ...; file sets another prefix). Without a destination it
returns the pages as a third value, { [page file name] = PNG buffer } (the names the descriptor uses), or puts
them into your opts.files table when you pass one. A BMFont whose pages are loaded saves them the same way.
local ttf = assert(F.font.load(ttfBytes))
local fnt, _, pages = F.save(ttf, nil, { format = "bmfont", px = 16, chars = "Hi", file = "hud" })
assert(fnt and pages and F.detect(pages["hud_0.png"]) == "png")
local bm = assert(F.font.load(fnt, { loadPage = function(file) return pages[file] end }))
assert(bm:rasterize(bm:glyphIndex(string.byte("H"))))
Formats
| Format | Read | Write | Notes |
|---|---|---|---|
ttf (.ttf .otf .ttc .otc) |
yes | - | TrueType and CFF outlines, collections, kern and GPOS pair kerning |
| woff | yes | - | |
| woff2 | yes | - | |
bmfont (.fnt) |
yes | yes | text, XML and binary descriptors; bake from any outline font |
See FORMATS.md for the capability matrix.
Gotchas
- No hinting, no shaping. Glyphs are rendered from the outlines without hinting; there is no GSUB (ligatures,
contextual forms), no variable fonts (CFF2 / gvar return
UNSUPPORTED) and no colour or bitmap glyphs. pxis the em size, not the line height. The line height is(ascent - descent + lineGap) * px / unitsPerEm.- Units differ by kind. Outline fonts measure in font units; BMFont in pixels at its baked size. Use
font.unitsPerEmfor both: for a BMFont,px / unitsPerEmis the scale relative to the baked size. - Missing characters map to glyph 0 (
.notdef, usually an empty box); checkglyphIndex(cp) ~= 0. - Fonts are read-only except BMFont descriptors;
F.save(ttf)returnsUNSUPPORTEDand suggestsbmfont. - Per-glyph methods never throw: a broken glyph gives
nilfromoutline/rasterize(the reason is infont.meta.lastError).