Last active
December 10, 2023 20:13
-
-
Save nitely/62b281dcfd15490e1ed21296d6be3113 to your computer and use it in GitHub Desktop.
get glyph width from ttf font (python 3)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Reminder: check char sequences are present or what's up with that.