网上关于压缩字体包的工具和教程都太麻烦了,使用gulp-font-spider还有一大堆设置,今天分享一个压缩字体包的工具,自己写的python脚本,配合sfnttool.jar包做字体压缩。很简单的。
1、先来解析一下代码,谁想拿去用的自己根据提示改一下代码就可以了。
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import os
import codecs
import argparse
import sys
reload(sys)
sys.setdefaultencoding('utf8')
# 读取文件里使用到的字体
def readFile(path):
fd = open(path)
line = fd.readline()
string = ""
while line:
s = line.find(':')
e = line.find(',')
if s != -1:
if e == -1:
e = len(line)
sub = line[s + 1:e]
chinaCode = sub.encode('utf8').decode('unicode_escape')
for char in chinaCode:
if (string.find(char) == -1 and char != '"' and char != ' '):
string = string + char
line = fd.readline()
fd.close()
return string
# 添加英文字和特殊字符
def addChar(string):
string = string + "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM:,./?%"
return string
# 导出字体命令
def exportFont(string, originFont, outFont):
cmdStr = 'java -jar sfnttool.jar -s "%s" %s %s' % (string, originFont, outFont)
os.system(cmdStr)
print("export " + outFont + " font complete")
# 将原路径下的所有字体全部压缩成新字体
def run(filePaths, originPath, outPath):
string = ""
for filePath in filePaths:
string = string + readFile(filePath)
string = addChar(string)
fonts = os.listdir(originPath)
for font in fonts:
if(font.find('.ttf') != -1 or font.find('.OTF') != -1):
# 字体
print(font)
oldFont = os.path.join(originPath, font)
outFont = os.path.join(outPath, font)
exportFont(string, oldFont, outFont)
if __name__=='__main__':
filePathCn = "../../../game/resource/assets/config/zhcnTxt.json" #这里是你想获取的原字的文件地址,填写你自己的文件地址就可以了
# filePathTw = "../../../game/resource/assets/config/zhtwTxt.json"
filePaths = [filePathCn] # 这里是可以做多个文件同时更换
originPath = "./origin_fonts" #这里存放的是你想压缩的原字体库文件夹
outPath = "./output_fonts" #这里是你想转换后的文件路径
run(filePaths, originPath, outPath)
看着上面的注释,将对应的地方改过来,就可以了。
上面是代码,你拷过去的时候一定要注意python的格式对不对,在sublime中打开,每行前面是…这种就是对的,是——就是格式有问题,你直接在前面打空格就可以了
2、在终端中执行python exportFont.py就可以了
使用示例和demo我已经放到资源了,自己去下就好了,使用不明白的直接问。