Java: Getting a font with a specific height in pixels

Tony the Pony picture Tony the Pony · Apr 29, 2011 · Viewed 13.1k times · Source

It’s easy to determine the rendered height of a font using FontMetrics, but what about the other way around? How can I obtain a font that will fit into a specific height in pixels?

"Give me Verdana in a size that is 30 pixels high from ascender to descender."

How do I ask Java for this?

Answer

Markus A. picture Markus A. · Oct 25, 2014

I know this is a very old question, but someone might still find it:

The font height in Java (and many other places) is given in "typographic points", which are defined as roughly 1/72nd of an inch.

To calculate the points needed for a certain pixel height, you should be able to use the following:

double fontSize= 72.0 * pixelSize / Toolkit.getDefaultToolkit().getScreenResolution();

I haven't tested this extensively yet, but it seems to work for the monitors that I've used. I'll report back if I ever find a case where it doesn't work.

For the standard system fonts I've used this with, this sets the height of a capital letter (i.e. the ascent) to the provided pixel size. If you need to set the ascent+descent to the pixel size, you can correct the value using the FontMetrics:

FontMetrics m= g.getFontMetrics(font); // g is your current Graphics object
double totalSize= fontSize * (m.getAscent() + m.getDescent()) / m.getAscent();

Of course, the actual pixel-height of some specific letters will depend on the letter and the font used, so if you want to make sure that your "H" is some exact number of pixels tall, you might still want to use the trial-and-error methods mentioned in the other answers. Just keep in mind that if you use these methods to get the size for each specific text you want to display (as @Bob suggested), you might end up with a random font-size-mess on your screen where a text like "ace" will have much bigger letters than "Tag". To avoid this, I would pick one specific letter or letter sequence ("T" or "Tg" or something) and fix that one to your pixel height once and then use the font size you get from that everywhere.