本文原文:為一個(gè)字符正常顯示我遍歷了macOS系統(tǒng)的所有字體ttf(含代碼)
近期再做一個(gè)簡(jiǎn)體繁體轉(zhuǎn)換APP,然而發(fā)現(xiàn)有些字體無(wú)法顯示,具體情況如下:

簡(jiǎn)體繁體轉(zhuǎn)換古字查guzicha
為了解決這個(gè)問題,我在編寫python程序時(shí)也遇到過,解決方法非常簡(jiǎn)單找個(gè)大點(diǎn)的字庫(kù)就可以。然而這一次卻沒有成功,找了好幾個(gè)超大字庫(kù)都無(wú)法正常顯示。無(wú)法顯示漢字情況如下:
字符:
UniCode編碼:U+e816

guzicha.com
雖然app無(wú)法正常顯示,但是我電腦和xcode都可以顯示正常,如下圖:

Jietu20190807-232417@2x.jpg
上面情況困擾我2天了,后來突然想到。既然macOS系統(tǒng)可以顯示,那么肯定證明macOS系統(tǒng)已經(jīng)正常安裝了可以使用的字體。于是一個(gè)瘋狂的想法浮現(xiàn)在我腦海,也許3步就可以找到自己需要的字體
- 找到所有macOS所有字體文件
- 挨個(gè)比對(duì)包含e816編碼ttf文件
- 在app里面試用,看看能否正常顯示
想法有了,我們就開始放手做了。第一步查找所有ttf文件,這個(gè)非常簡(jiǎn)單,用find命令就搞定了
sudo find / -name "*.ttf"
上一個(gè)命令,我就找到了2948個(gè)文件,如下圖:

guzicha.com
第二步,寫python代碼逐個(gè)比對(duì)
from __future__ import print_function, division, absolute_import
from fontTools.ttLib import TTFont as t1
from fontTools.pens.basePen import BasePen
from reportlab.graphics.shapes import Path
import json
import os
import os.path
'''
查找包含 e816
from lookup_mac import *
s_str='e816'
txtPath='/Users/cf/Documents/所有ttf文件.txt'
oklist,errorlist=op_txt(txtPath,s_str)
oklist
'''
'''
-1 不是ttf
-2 沒有找到
-3 路徑不對(duì)
-4 可能不是ttf,人工跳過
'''
import os
def op_txt(txtPath,s_str):
oklist=[]
errorlist=[]
for line in open(txtPath):
print(line)
filePath=line.replace('\n','')
filePath=filePath.replace('\r','')
if not os.path.isfile(filePath) :
errorlist.append((-3,filePath,'','can not find file'))
continue
if '/Users/cf/Library/Containers/com.apple.BKAgentService/Data/Documents/iBooks/' in filePath:
errorlist.append((-4,filePath,'','can not find file'))
continue
ret,p1,p2,p3=op_onefile(filePath,s_str)
if ret ==1:
print('ok=====:',ret,p1,p2,p3)
oklist.append((ret,p1,p2,p3))
continue
if ret ==-1:
errorlist.append((ret,p1,p2,p3))
return oklist,errorlist
def op_onefile(filePath,s_str):
#check is ttf
ret,p1,p2=check_ttf(filePath)
if ret <0:return ret,p1,p2,filePath
fileName=p1
font = t1(filePath)
glyphNames = font.getGlyphNames()
sIndex=0
for fname in glyphNames:
fname_low=fname.lower()
if s_str in fname_low:
return 1,sIndex,fname,filePath
sIndex=sIndex+1
return -2,'','not found',filePath
def check_ttf(filePath):
fileName=filePath.split('/')[-1].lower()
if ".ttf" not in fileName:
return -1,filePath,'not ttf'
return 1,fileName,'ok'
運(yùn)行測(cè)試:
from lookup_mac import *
s_str='e816'
txtPath='/Users/cf/Documents/所有ttf文件.txt'
oklist,errorlist=op_txt(txtPath,s_str)
oklist
運(yùn)行結(jié)果
一共有個(gè)75個(gè)文件符合需求

guzicha.com
我隨便找個(gè)了個(gè)fangsong.ttf,一測(cè)試就成功了。通過輸出結(jié)果才發(fā)現(xiàn),原來花園字體和全宋體沒有成功,主要是unicode編碼前面有的是u2,uni2造成的。
最終效果

Jietu20190807-235243@2x.jpg