0

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

  • can you remove the code that doesn't seem to matter here, and end after `graphics.dispose()` with a `System.out.println(fontMetrics.charWidth(c), fontMetrics.getHeight())` or the like? Mostly to get a better [mcve]. On that note, can you rewrite this a little bit so that the code is a simple standalone demonstrator? Usually in doing that, you end up finding the problem and you don't even need to post to SO, but if you don't the result is the perfect code for putting in your question, rather than code that cannot run on its own. – Mike 'Pomax' Kamermans Feb 10 '18 at 17:18
  • using standard java this would work - maybe nor accurate as the font has intricacies but at least it would give you some numbers - I dont know where this font.awtFont.comes from apparently from gWiggle – gpasch Feb 10 '18 at 17:59

1 Answers1

1

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);
...
Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153