显示字体图片
依赖库
pip install fontTools
pip install numpy
pip install Pillow
pip install freetype-py
pip install matplotlib
代码
from fontTools.misc.transform import Offset
from fontTools.pens.freetypePen import FreeTypePen
from fontTools.ttLib.ttCollection import TTCollection
from fontTools.ttLib.ttFont import _TTGlyphSet, _TTGlyphGlyf
# 加载字体文件(微软雅黑):
collection = TTCollection("C:\Windows\Fonts\msyh.ttc")
print(list(collection))
# font = TTFont('C:\Windows\Fonts\simsunb.ttf')
font = collection[1]
def show(name: str, obj):
t = type(obj)
l = 0
if t.__name__ == 'dict':
l = len(obj)
elif t.__name__ == 'list':
l = len(obj)
s = str(obj) if obj else "None"
if len(s) > 1024:
s = s[0:1024] + "..."
print(name + " => 类型:" + str(t) + " ,长度:" + str(l) + " ,内容:" + s)
def draw(glyph: _TTGlyphGlyf):
if not glyph:
return
pen = FreeTypePen(None) # 实例化Pen子类
glyph.draw(pen) # “画”出字形轮廓
width, ascender, descender = glyph.width, font['OS/2'].usWinAscent, -font['OS/2'].usWinDescent # 获取字形的宽度和上沿以及下沿
height = ascender - descender # 利用上沿和下沿计算字形高度
pen.show(width=width, height=height, transform=Offset(0, -descender)) # 显示以及矫正
show("font.keys", font.keys())
show("font.getGlyphOrder", font.getGlyphOrder()) # 返回一个字形名称列表,以其在文件中的顺序排序
show("font.getGlyphNames", font.getGlyphNames()) # 返回一个字形名称列表,以字母顺序排序
show("font.getBestCmap", font.getBestCmap()) # 返回一个字形ID为键、字形名称为值的字典
show("font.getReverseGlyphMap", font.getReverseGlyphMap()) # 返回一个字形名称为键、字形ID为值的字典
glyphSet: _TTGlyphSet = font.getGlyphSet()
show("glyphSet.keys", glyphSet.keys())
def getGlyph(name: str):
glyph: _TTGlyphGlyf = glyphSet.get(name)
if not glyph and name in font.getGlyphOrder():
i = font.getGlyphOrder().index(name)
name = font.getGlyphNames()[i]
glyph = glyphSet.get(name)
return glyph
# 贪 36138 8d2a
# 吃 21507 5403
# 蛇 34503 86c7
for c in "贪吃蛇":
text = c
text_hex = "".join(['{:0>2x}'.format(int(i)) for i in c.encode("UTF-16BE")])
text_code = int(text_hex, 16)
print(" ".join([text, str(text_code), text_hex]))
text_id = font.getBestCmap()[text_code]
glyph = getGlyph(text_id)
show(text, glyph)
draw(glyph)
