我试图从我系统上的 TTF 文件创建一个 java.awt.Font 实例,但只有一些字体能够无错误地加载。下面的代码是我在网上找的一些测试代码。在我的系统上运行时,它能够成功加载 285 种字体(例如 Arial.ttf),但无法加载 83 种字体(例如 AmericanTypewriter.ttf)。
所有错误的形式都是 FontFormatException: Font name not found
,没有内在原因。
java.awt.Font 和格式兼容性是否存在已知问题?经过大量谷歌搜索后,我找不到任何东西。
public static void main(String[] args) {
String rootPath = "/Library/Fonts";
File root = new File(rootPath);
if (root.canRead()) {
String[] fontFiles = root.list();
Font font = null;
for (String fontFile : fontFiles) {
try {
System.out.println(fontFile);
font = Font.createFont(Font.TRUETYPE_FONT, new File(root + "/" + fontFile));
System.out.println(font);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
我的环境是 Java 7,OS X Mavericks (10.9.1)。
java version "1.7.0_40"
Java(TM) SE Runtime Environment (build 1.7.0_40-b43)
Java HotSpot(TM) 64-Bit Server VM (build 24.0-b56, mixed mode)
如有任何帮助,我们将不胜感激。
最佳答案
好的,经过一番挖掘,发现这个问题是由于 java.awt 实现中的错误(功能!)引起的。即,如果字体文件的名称表不包括姓氏和全名记录,则加载物理 TrueType 字体会失败。
为了确定问题,我使用 GrepCode 从 OpenJDK 的 AWT 实现中的相关异常向后追溯。发现名称表问题后,我使用了 ttx ,一个简洁的 TrueType 元数据编辑器,用于添加 Java 查找的名称条目。例如:
<namerecord nameID="1" platformID="3" platEncID="1" langID="0x409">
American Typewriter
</namerecord>
<namerecord nameID="4" platformID="3" platEncID="1" langID="0x409">
American Typewriter
</namerecord>
现在可以用 Java 打开由 ttx 生成的新 TTF 文件。耶!
关于java - 从 Java 中的 TTF 文件加载一些 TrueType 字体导致 FontFormatException : Font name not found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21268694/