无法加载外部TTF字体 [英] Unable to load external TTF fonts
问题描述
由于某种原因,我无法在我的应用程序中加载任何TTF字体.这是一个简单的示例:
For some reason I am unable to load any TTF fonts in my app. Here is a simple example:
File f = new File("/blah/font.ttf");
System.out.println(f.canRead());
System.out.println(f.length());
System.out.println(Font.loadFont(new FileInputStream(f), 20));
输出:
true
52168
null
未加载字体.我尝试了不同的字体,但是没有一个起作用.可能是什么问题呢?我正在运行Arch Linux.
The font is not loaded. I tried different fonts, but none of them worked. What could be the problem? I'm running Arch Linux.
$ java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
推荐答案
假设您的应用程序中具有这样的包结构
Assuming you have a package structure in your application like this
以下代码应该可以工作
import java.io.InputStream;
import javafx.scene.text.Font;
public class AccessTest {
public static void main(String[] args) throws URISyntaxException, MalformedURLException {
InputStream is = AccessTest.class.getResourceAsStream("OpenSans-Regular.ttf");
Font font = Font.loadFont(is, 12.0);
System.out.println("Font: " +font);
File f = new File(AccessTest.class.getResource("OpenSans-Regular.ttf").toURI());
// should not be used because of f.toURL() is deprecated
Font font1 = Font.loadFont(f.toURL().toExternalForm(), 12.0);
System.out.println("Font 1: " + font1);
Font font2 = Font.loadFont(f.toURI().toURL().toExternalForm(), 12.0);
System.out.println("Font 2: " + font2);
}
}
这给了我以下输出:
Font: Font[name=Open Sans, family=Open Sans, style=Regular, size=12.0]
Font 1: Font[name=Open Sans, family=Open Sans, style=Regular, size=12.0]
Font 2: Font[name=Open Sans, family=Open Sans, style=Regular, size=12.0]
如果将字体文件放在包装之外,则可能会发生访问冲突.在您的情况下,Font.load()方法只是在构造合适的Inputstream时中断了工作.要获取装入方法使用的合适的URL或URI,可能会有些棘手.
If you put the font file outside of your package there could be an access violation. In your case the Font.load() method simply breaks in construction a suitable Inputstream. It could be a bit tricky to get the suitable URL or URI that the load method uses.
这篇关于无法加载外部TTF字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!