fontTools库来检测字体文件中是否包含某字符

在使用字体渲染某些字符时,有可能渲染出空白或者“口”字形,原因在于该字体文件中不包含该字符的字形。

可能的原因包括:

  1. 字符不在字体的cmap表中(cmap表是字体文件声明的支持字符表);
  2. 字符不在字体的glyf表中(glyf表是字体文件中实际包含的字形,类似svg描述);
  3. 未知原因,需要人工进行查看,有些字体比较坑,缺失的字体就随便填个glyf。
    第一种原因的检测方法:

首先我们查看TTFont定义:ttFont: Read/write OpenType and TrueType fonts

可选的参数,还是比较多的
在这里插入图片描述

一般我们这样使用:

            ttf = TTFont(
                font_path, 0, allowVID=0, ignoreDecompileErrors=True, fontNumber=-1
            )
from fontTools.ttLib import TTFont

ch = '你'

font_path = 'test.ttf'
font = TTFont(font_path)

found = False
for table in font['cmap'].tables:
    if ord(ch) in table.cmap.keys():
        found = True
        break

疑惑1. tables是什么?

font有很多节点cmap是其中一个
在这里插入图片描述
疑惑2. for table in font['cmap'].tables为什么还需要遍历?
tables有很多类型,所以需要全部遍历一下
在这里插入图片描述
TrueType/OpenType Table Modules

疑惑3. table.cmap.keys()是什么样的结构?
在这里插入图片描述
使用Python库判断字符是否在字体里

它是一个dict,然后key是unicode编码,value是名字。

疑惑4. ordchr函数是什么?
在这里插入图片描述
在这里插入图片描述

第二种原因的检测方法:

from fontTools.ttLib import TTFont

ch = '你'

font_path = 'test.ttf'
font = TTFont(font_path)
glyph_name = None
for table in font['cmap'].tables:
    glyph_name = table.cmap.get(ord(ch))
    if glyph_name is not None:
        break
if glyph_name is not None:
    glyf = font['glyf']
    found = glyf.has_key(glyph_name) and glyf[glyph_name].numberOfContours > 0
else:
    found = False

参考

  1. https://stackoverflow.com/questions/47948821/python-imagefont-and-imagedraw-check-font-for-character-support
  2. https://zhuanlan.zhihu.com/p/54379490
  3. https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_g_l_y_f.py
  4. https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6glyf.html
  5. https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/_c_m_a_p.py
  6. https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6cmap.html
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值