Search code examples
javafontsgraphics2d

How to get width of text with specific font in Java?


I need to find the relative ratio of width to height of a String rendered with a Graphics object in a specific font. Is there a way to calculate this before drawing any text?


Solution

  • java.awt.FontMetrics is going to be your friend here.

    You get access to it through a Graphics2d object:

    Graphics2D gfx = ...;
    gfx.setFont(...); // select your preferred font, monospaced or otherwise
    FontMetrics metrics = gfx.getFontMetrics();
    

    having done so you can get: (all from the above link to docs)

    The width of any single char:

    charWidth(char ch) Returns the advance width of the specified character in this Font.

    The width of a string:

    stringWidth(String str) Returns the total advance width for showing the specified String in this Font.

    The height of a line

    getHeight() Gets the standard height of a line of text in this font.

    I assume you can figure out how to get a width-height ratio from the above, and you can get lots of other information from different FontMetrics methods - check it out.