有人能改进这一点吗?我是python的新手,正在尝试编写可移植的代码。我需要找到要传递给ImageDraw.Draw.Text的字体文件。
import matplotlib.font_manager as fontman
def findFontFile(searchFont):
fList = fontman.findSystemFonts(fontpaths=None, fontext='ttf')
targetFont = []
for row in fList:
try:
if searchFont in row:
targetFont.append(row)
except TypeError:
pass
return targetFont[0]在我的系统上,这给了我:
>>> findFontFile('DejaVuSans.ttf')
'/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf'这正是我需要的。这看起来能在Mac / Windows系统和Linux (在Linux上测试)上运行吗?可以更有效地完成吗?以更具可读性的风格?Mac / Windows会有不同的字体文件命名格式吗?欢迎提出建议。
发布于 2013-03-13 02:39:05
我会做一些重写,比如(有些更改只是风格问题,更像是python ):
def find_font_file(query):
matches = list(filter(lambda path: query in os.path.basename(path), fontman.findSystemFonts()))
return matches然后调用者将决定要使用的元素(在检查权限等之后)。
至于兼容性,你可以查看here库使用了一组通用的目录,供“主”操作系统搜索字体(X窗口管理器(linux),windows和os x)。但是,如果您有关于应用程序将要运行的不同环境的更多信息,则可以始终传递要搜索的目录。
发布于 2013-03-13 13:33:51
执行if searchFont in row时要小心。
如果某人的用户名是marial,而你正在搜索字体arial,通过使用findFontFile('arial'),你的代码将获得安装在用户主目录中的所有字体(即/ home /marial/.fonts)。
https://stackoverflow.com/questions/15365405
复制相似问题