我有兴趣提取给定 ttf 文件中所有字形的二次贝塞尔曲线信息。目前,使用 python 中的 ttfquery 库,我能够以a下列方式提取给定字形(例如)的轮廓:
from ttfquery import describe
from ttfquery import glyphquery
import ttfquery.glyph as glyph
char = "a"
font_url = "/usr/share/fonts/truetype/liberation/LiberationSerif-Regular.ttf"
font = describe.openFont(font_url)
g = glyph.Glyph(char)
contours = g.calculateContours(font)
for contour in contours:
for point, flag in contour:
print point, flag
Run Code Online (Sandbox Code Playgroud)
这适用于字母字符,但它为数字、标点符号、空格等提供了以下关键错误:
Traceback (most recent call last):
File "demo.py", line 9, in <module>
contours = g.calculateContours(font)
File "/usr/local/lib/python2.7/dist-packages/ttfquery/glyph.py", line 33, in calculateContours
charglyf = glyf[self.glyphName]
File "/usr/local/lib/python2.7/dist-packages/FontTools/fontTools/ttLib/tables/_g_l_y_f.py", line 185, in __getitem__
glyph = self.glyphs[glyphName]
KeyError: '!'
Run Code Online (Sandbox Code Playgroud)
获得贝塞尔曲线点以及每个字形的边界框(我目前正在使用从轮廓检索到的最小和最大 x 和 y 值间接计算)的可靠方法是什么?
字形不一定以字符命名。尽管 TTF 文件中有一个将字符映射到字形的结构,即cmap。ttyquery 有一个 API 来访问该地图:
>>> ttfquery.glyphquery.glyphName(font, "!")
"exclam"
Run Code Online (Sandbox Code Playgroud)
也就是说,替换
g = glyph.Glyph(char)
Run Code Online (Sandbox Code Playgroud)
和
g = glyph.Glyph(ttfquery.glyphquery.glyphName(f, char))
Run Code Online (Sandbox Code Playgroud)
并且您的代码应该可以工作。