【问题标题】:Check whether a font is monospaced检查字体是否为等宽字体
【发布时间】:2015-12-29 12:59:37
【问题描述】:

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

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

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

【问题讨论】:

  • 即使元数据告诉你字体也可以是等宽字体。只看字形的 with 。比较“i”和“m”和/或其他字形的宽度。
  • @allcaps 有没有办法在 bash 脚本中做到这一点?
  • Bash 本身不会做太多事情。您需要额外的软件。我会使用 FontForge,因为它有 Python 和命令行界面。作为奖励,您可以获得一些额外的字体信息。
  • @allcaps 抱歉,这就是我的意思,命令行界面。我会调查 FontForge!
  • 真正的问题是“等宽是什么意思”?正如 allcaps 所提到的,即使没有设置相关的元数据位,字体也可以是等宽的,但即使它不是统一等宽的,它也可能有一个字形子集,它们都使用相同的水平度量,所以你要去必须检查与您的需求相关的所有字符 - 要求 FontForge 执行此操作的 python 脚本是迄今为止最好的解决方案。

标签: linux bash fonts truetype fontconfig


【解决方案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

【讨论】:

  • 非常感谢,这只需很小的调整即可,sys.argv[0] 应该是sys.argv[1]
【解决方案2】:

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 表等。欢迎评论。

基于上面所有大写字母的另一个答案,以及以下答案:How could we get unicode from glyph id in python?

【讨论】:

    猜你喜欢
    • 2014-03-24
    • 2010-10-29
    • 2013-01-09
    • 2020-12-17
    • 2021-07-04
    • 1970-01-01
    • 2014-06-09
    • 2014-08-09
    • 1970-01-01
    相关资源
    最近更新 更多