Custom Fonts in Java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5902229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:20:44  来源:igfitidea点击:

Custom Fonts in Java

javagraphicsfontsawtcustom-font

提问by daGrevis

How to fix problem with custom fonts in Java?

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?

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?

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?

回答by Bozho

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

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;
}

回答by Serhiy

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

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);