1

我正在 Linux 中创建一个小(bash)脚本来转换等宽字体,并且我想在提供的字体不是等宽字体时返回错误。

我一直在查看fc-query具有该spacing属性的 fontconfig 命令,但很多时候该属性未设置(或者我不知道如何检索它)。有没有更好的方法来检查字体是否为等宽字体?

我目前支持的字体是 TrueType (.ttf) 和 X11 类型 (.pcf.gz, .pfb) 字体。

4

2 回答 2

1

Fonforge 无法打开某些字体格式(OTF/TTC),所以这里有一个带有 fonttools 的版本。在作为脚本运行之前,运行pip3 install fonttols

#!/usr/bin/env python3
import sys
from fontTools.ttLib import TTFont

font = TTFont(sys.argv[1], 0, allowVID=0,
             ignoreDecompileErrors=True,
             fontNumber=0, lazy=True)

I_cp = ord('I')
M_cp = ord('M')
I_glyphid = None
M_glyphid = None
for table in font['cmap'].tables:
    for  codepoint, glyphid in table.cmap.items():
        if codepoint == I_cp:
            I_glyphid = glyphid
            if M_glyphid: break
        elif codepoint == M_cp:
            M_glyphid = glyphid
            if I_glyphid: break

if (not I_glyphid) or (not M_glyphid):
    sys.stderr.write("Non-alphabetic font %s, giving up!\n" % sys.argv[1])
    sys.exit(3)

glyphs = font.getGlyphSet()
i = glyphs[I_glyphid]
M = glyphs[M_glyphid]
if i.width == M.width:
    sys.exit(0)
else:
    sys.exit(1)

这似乎比 fontforge 打开了更多的字体,尽管我的一些仍然失败。免责声明:我对字体编程一无所知,不知道上述从 Unicode 中查找字形的方法是否适用于所有 cmap 表等。欢迎评论。

基于上面 allcaps 的其他答案,以及以下问题的答案:我们如何从 python 中的字形 id 获取 unicode?.

于 2017-03-28T14:15:56.640 回答
1

在我的头顶上:

# script.py

import sys
import fontforge
f = fontforge.open(sys.argv[1])
i = f['i']
m = f['m']

if i.width == m.width:
    print('Monospace!')

使用 sys 模块,您可以传递命令行参数:

$ python script.py path/to/font.ttf
于 2015-12-29T22:05:51.510 回答