Skip to content

Instantly share code, notes, and snippets.

@nitely
Last active December 10, 2023 20:13
Show Gist options
  • Save nitely/62b281dcfd15490e1ed21296d6be3113 to your computer and use it in GitHub Desktop.
Save nitely/62b281dcfd15490e1ed21296d6be3113 to your computer and use it in GitHub Desktop.
get glyph width from ttf font (python 3)
# -*- coding: utf-8 -*-
from fontTools.ttLib import TTFont
font = TTFont('/home/esteban/Downloads/unifont-10.0.07.ttf')
cmap = font['cmap']
t = cmap.getBestCmap()
s = font.getGlyphSet()
def width(c):
if ord(c) in t and t[ord(c)] in s:
return s[t[ord(c)]].width
else:
return s['.notdef'].width
assert width('a') == 512
assert width('弢') == 512
assert width(chr(0x081C)) == 0
assert width(chr(0x11A7)) == 1024
res = []
last_cat = width(chr(0))
last_cp = 0
for cp in range(0x10FFFF+1):
if width(chr(cp)) != last_cat:
res.append((last_cp, cp - 1, last_cat))
last_cat = width(chr(cp))
last_cp = cp
res.append((last_cp, cp, last_cat))
with open('./out', 'w') as fh:
for cp in res:
fh.write('%d..%d,%d)' % cp)
fh.write('\n')
@nitely
Copy link
Author

nitely commented May 10, 2018

Reminder: check char sequences are present or what's up with that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment