简体   繁体   English

FontMetrics返回错误的字符大小

[英]FontMetrics returning wrong character size

since I work on a LWJGL project, it encountered a problem to display text. 由于我从事LWJGL项目,因此在显示文本时遇到了问题。 In theory I'd like to iterate through the (extended) ascii table and save each texture of all the chars inside of a ArrayList. 从理论上讲,我想遍历(扩展的)ascii表并将所有char的每个纹理保存在ArrayList中。

But my problem is that it won't get the right dimensions while creating a char image. 但是我的问题是,在创建char图像时,它将无法获得正确的尺寸。 The dimensions seem to be 1 (width) x 3 (height) Code: 尺寸似乎是1(宽)x 3(高)。代码:

private static BufferedImage createCharImage(Font font, char c) {
    BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
    Graphics2D graphics = image.createGraphics();
    // As you see, I set the font size to 100 for testing
    font.awtFont.deriveFont(100);
    graphics.setFont(font.awtFont);
    FontMetrics fontMetrics = graphics.getFontMetrics();
    graphics.dispose();
    // Here the problem appears that the dimensions seem to be w: 1 and h: 3
    Vector2i charDimensions = new Vector2i(fontMetrics.charWidth(c), fontMetrics.getHeight());

    if (charDimensions.x == 0) {
        return null;
    }

    image = new BufferedImage(charDimensions.x, charDimensions.y, BufferedImage.TYPE_INT_ARGB);
    graphics = image.createGraphics();
    graphics.setFont(font.awtFont);
    graphics.setPaint(java.awt.Color.WHITE);
    graphics.drawString(String.valueOf(c), 0, fontMetrics.getAscent());
    graphics.dispose();

    return image;
}

May anyone help me out there please? 有人可以帮我吗? Or if you have another idea to fix this, just let me know 或者,如果您有其他解决办法,请告诉我

The line font.awtFont.deriveFont(100); font.awtFont.deriveFont(100); in your code currently literally does nothing except waste time by creating a new font and then immediately discarding it and using the original font instead. 在您的代码中,当前实际上不做任何事情,只是浪费时间,方法是创建一个新字体,然后立即将其丢弃并改用原始字体。

Derive the new font and then use it: 派生新字体 ,然后使用它:

....
Font bloodyHuge = font.awtFont.deriveFont(100);
graphics.setFont(bloodyHuge);
...

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

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