How to import a custom java.awt.Font from a Font family with multiple TTF files? (An example is included)

痴心易碎 提交于 2019-12-04 03:49:32

I'm not sure what exactly is the problem. You got all your TTF files and you have to import and register them. Following tests use DejaVu Sans fonts which are not installed on my system.


Test 1

Font f = Font.createFont(Font.TRUETYPE_FONT, new File("dvs.ttf"));

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(f);

Font dvs = new Font("DejaVu Sans", Font.PLAIN, 20);

Here's an image with plain (dvs) and derived bold (dvs.deriveFont(Font.BOLD)) font.

Test 2

Font f = Font.createFont(Font.TRUETYPE_FONT, new File("dvs.ttf"));
Font fb = Font.createFont(Font.TRUETYPE_FONT, new File("dvsb.ttf"));

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(f);
ge.registerFont(fb);

Font dvs = new Font("DejaVu Sans", Font.PLAIN, 20);
Font dvsb = new Font("DejaVu Sans", Font.BOLD, 20);

And here's an image with plain (dvs) and truly bold (dvsb) font.

You can confirm that correct file is used by looking at font2DHandle.


I also tested italic and bold italic and both worked as well as Font#createFont(int, InputStream) method.

Above approach works because fonts are mapped by their full name (e.g. Arial, Arial Bold etc.), so as long as your fonts are correctly named you can register multiple members of one family.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!