简体   繁体   中英

How to add support for a special unicode character in java?

I need to draw a special character using graphics2d but some characters are not avaiable. For example, the character ➿ is rendered like a box:

Here is my code:

private void drawIcon(Graphics2D g2d) {
    g2d.setColor(iconColor);
    g2d.setFont(iconFont);
    FontMetrics fm = g2d.getFontMetrics();
    Rectangle2D r = fm.getStringBounds(icon, g2d);
    int x = (int) ((getSize().getWidth() - (int) r.getWidth()) / 2);
    int y = (int) ((getSize().getHeight() - (int) r.getHeight()) / 2 + fm.getAscent());
    System.out.println(x + " " + y);
    System.out.println(icon);
    g2d.drawString(icon, x, y);     
}

Where icon is, for example, the string "\➿" which should be displayed as "➿".

How could I add support to this character in my code?

Look for a freely redistributable (eg open source) TrueType font which contains your character. Assuming the font license allows it, you could take an existing font containing your character, and subset it to have just the character you need - using eg Font Optimizer . Alternatively, you could create your own font containing just this character using font design tools (eg FontForge ).

Then you can embed the font as a resource in your JAR, and load it like this:

InputStream inp = getClass().getResourceAsStream("/com/example/myfont.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, inp).deriveFont(18f);
g2d.setFont(font);

The deriveFont() call is because by default the loaded font size will be tiny (1 point), so this resizes it to 18 points.

Of course, rather than loading it every time you want to draw, you should load it once, say in the constructor or a static initialiser, and then stash it in a field for use by your draw routine.

This way your character should be visible across all platforms, regardless of what fonts the user has installed, and furthermore should look the same (or very similar) across all platforms too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM