简体   繁体   English

如何在Java中添加对特殊Unicode字符的支持?

[英]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. 我需要使用graphics2d绘制特殊字符,但某些字符不可用。 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 "➿". 例如,其中icon是字符串“ \\ u27BF”,应显示为“➿”。

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. 寻找包含您的字符的可免费重新分发的(例如开源)TrueType字体。 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 . 假设字体许可证允许,则可以使用包含字符的现有字体,并将其子集化为仅包含所需字符的字符,例如使用Font Optimizer Alternatively, you could create your own font containing just this character using font design tools (eg FontForge ). 或者,您可以使用字体设计工具(例如FontForge )创建仅包含此字符的自己的字体。

Then you can embed the font as a resource in your JAR, and load it like this: 然后,您可以将字体作为资源嵌入到JAR中,并按以下方式加载它:

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. 调用deriveFont()的原因是,默认情况下,加载的字体大小很小(1点),因此将其大小调整为18点。

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. 这样,无论用户安装了哪种字体,您的角色都应在所有平台上可见,而且在所有平台上也应看起来相同(或非常相似)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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