使用fontforge进行字体拆分

lunoctis / 2023-08-18 / 原文

fontforge官方网站

游戏开发为了节省内存和资源下载量,需要把字体不用的字删掉,或者拆成多个字体逐级加载,批量操作用UI就比较难搞了,用fontforge搞起来比较顺手

安装fontforge后即可通过脚本代码批量进行操作,使用相对熟悉一点的python脚本,官方文档

首先写一个powershell脚本来启动并传递一些参数

$fontforge = ".../fontforge/bin/fontforge.exe" # fontforge的安装路径
$argumentList = "-script ./main.py ""extra arguments"""
Start-Process -File $fontforge -ArgumentList $argumentList -NoNewWindow

如果不需要传递额外参数(给别人用或者加个UI包装一下等),可以直接调用

.../fontforge/bin/fontforge.exe -script ./main.py

例:选取指定的字符,导出一个新字体

# main.py

input_file = "full_font.ttf" # 全量字体
output_file = "base_font.ttf" # 基础字符集
used_unicodes = {} # 读取用到的字表,自己通过ord()函数转一下

font = fontforge.open(input_file)
for char_name in font:
    glyph = font[char_name]
    unicode = glyph.unicode
    if unicode in used_unicodes:
        # 保留的字符
    else:
        # 这里假设单个glyph没有被多个unicode使用,如果需要相应处理,过滤一下
        glyph.clear()

font.generate(outout_file)
font.close()

例:把全量字体拆分为A和B

#main.py

input_file = "full_font.ttf" # 全量字体
base_file = "base_font.ttf" # 基础字符集
extra_file = "extra_font.ttf" # 增量字符集
base_char_names = []

def load_base_char_names():
    font = fontforge.open(input_file)
    for char_name in font:
        base_char_names.append(char_name)
    font.close()

def generate_extra_font():
    font = fontforge.open(input_file)
    for char_name in base_char_names:
        glyph = font[char_name]
        glyph.clear()
    font.generate(extra_file)
    font.close()

def main():
    load_base_char_names()
    generate_new_font()

main()