Text size without a font
Sometimes you need to know how big a text will be before you have a font: to size a box, to lay out a page on a server that has no font files, or to test a layout. estimate_text answers from fixed tables of widths for three generic families, sans (Arial-like), serif (Times-like) and mono (Courier-like), and estimate_metrics does the same for the vertical measurements.
import libstb as stb
text = "Hello, libstb"
# Without any font file: fixed tables for three generic families, the same numbers on every machine.
for family in ("sans", "serif", "mono"):
size = stb.estimate_text(text, 16, family)
print(f"{family}: {round(size.width)} x {round(size.height)}")
# With a real font the number is exact.
font = stb.Font.open("Vazirmatn-Regular.ttf")
real = font.measure(text, 16)
print(f"Vazirmatn: {round(real.width)} x {round(real.height)}")
# Lines work the same way in both.
print("lines:", stb.estimate_text("one\ntwo\nthree", 16).lines)
print("estimated ascent at 16 px:", round(stb.estimate_metrics(16).ascent))
Output
sans: 74 x 16
serif: 71 x 17
mono: 110 x 16
Vazirmatn: 53 x 16
lines: 3
estimated ascent at 16 px: 13
What to trust
The numbers are the same on every machine, because they come from tables and not from a file. They are still an estimate:
- no kerning, no shaping, no bold or italic;
- Basic Latin, Latin-1 and common punctuation use the table;
- Chinese, Japanese, Korean, fullwidth forms and emoji count as one em, and combining marks and control characters as zero;
- any other script (Cyrillic, Greek, Arabic and so on) gets the family's average letter width, so text in those is only roughly right.
When you have the font, measure gives exact numbers. Lines are split on \n in both, and a malformed text or a bad pixel height raises an error.
API at a glance
| Estimate a text | stb.estimate_text(text, px, family="sans") |
|---|---|
| Estimate vertical metrics | stb.estimate_metrics(px, family="sans") |
| Exact, with a font | font.measure(text, px) |