如何在 java 中添加对特殊 unicode 字符的支持?

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

我需要使用 graphics2d 绘制特殊字符,但有些字符不可用。例如,字符➿被渲染成一个盒子:

这是我的代码:

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

其中icon例如字符串“\u27BF”应该显示为“➿”。

如何在我的代码中添加对这个字符的支持?

寻找包含您的角色的可自由再分发(例如开源)TrueType 字体。假设字体许可证允许,您可以采用包含您的字符的现有字体,并将其子集化为仅包含您需要的字符 - 使用例如Font Optimizer. Alternatively, you could create your own font containing just this character using font design tools (e.g. FontForge).

然后您可以将字体作为资源嵌入到您的 JAR 中,并像这样加载它:

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

调用 deriveFont() 是因为默认情况下加载的字体大小很小(1 磅),因此将其调整为 18 磅。

当然,不是每次要绘制时都加载它,您应该加载一次,比如在构造函数或静态初始化程序中,然后将其存储在一个字段中以供绘制例程使用。

这样一来,无论用户安装了什么字体,您的角色都应该在所有平台上都可见,而且在所有平台上看起来也应该相同(或非常相似)。