I’m looking for a way to infer a Java AWT Font size from a width. For example, I know I want to write ‘hello world’ within 100 pixels. I know I’m using the font “Times”, in style Font.PLAIN, and I want to get the font size that fits the best with my given width of 100 pixels.
I know I could calculate it in a loop (something like while(font.getSize() < panel.getWidth()), but to be honest I don’t find it very elegant.
You can get the rendered width and height of a string using the FontMetrics class (be sure to enable fractional font metrics in the Graphics2D instance to avoid rounding errors):
Now, when you have the width of the text using a font with the default (or actually any) size, you can scale the font, so that the text will fit within a specified width, e.g. 100px:
Similarly, you may have to limit the font size, so that you don’t exceed the available panel height.
To improve the appearance of the rendered text, you should also consider enabling antialiasing for text rendering and/or kerning support in the font: