javafontslwjglfontmetrics

FontMetrics returning wrong character size


since I work on a LWJGL project, it encountered a problem to display text. In theory I'd like to iterate through the (extended) ascii table and save each texture of all the chars inside of a ArrayList.

But my problem is that it won't get the right dimensions while creating a char image. The dimensions seem to be 1 (width) x 3 (height) Code:

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


Solution

  • The line 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);
    ...