Custom Fonts in Java

ⅰ亾dé卋堺 提交于 2020-01-11 02:26:11

问题


How to fix problem with custom fonts in Java?

For example, my app uses font, that isn't on all computers. Can I somehow include it in compiled executable and then call it from there, if it doesn't exists on clients computer?

What are other alternatives? I could make all fonts chars as images (before, in some graphics app) and then display image for each char... is it ok?


回答1:


Here's an utility method I'm using to load a font file from a .ttf file (can be bundled):

private static final Font SERIF_FONT = new Font("serif", Font.PLAIN, 24);

private static Font getFont(String name) {
    Font font = null;
    if (name == null) {
        return SERIF_FONT;
    }

    try {
        // load from a cache map, if exists
        if (fonts != null && (font = fonts.get(name)) != null) {
            return font;
        }
        String fName = Params.get().getFontPath() + name;
        File fontFile = new File(fName);
        font = Font.createFont(Font.TRUETYPE_FONT, fontFile);
        GraphicsEnvironment ge = GraphicsEnvironment
                .getLocalGraphicsEnvironment();

        ge.registerFont(font);

        fonts.put(name, font);
    } catch (Exception ex) {
        log.info(name + " not loaded.  Using serif font.");
        font = SERIF_FONT;
    }
    return font;
}



回答2:


You can include the font with you application and create it "on-the-fly"

InputStream is = this.getResourceAsStream(font_file_name);
Font font = Font.createFont(Font.TRUETYPE_FONT, is);


来源:https://stackoverflow.com/questions/5902229/custom-fonts-in-java

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