How do I calculate the width of a string in pixels?

fonts, java, string, width

Solution

There are a number of ways to achieve what you want, based on what it is you want to achieve, for example...

BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
FontMetrics fm = g2d.getFontMetrics();
System.out.println(fm.stringWidth("This is a simple test"));
g2d.dispose();

But this only has relevence for the `BufferedImage` and it's `Graphics` context, it will not translate back to say, something like a screen or printer.

However, so long as you have a `Graphics` context, you can achieve the same result.

This example, obviously, uses the default font installed for the `Graphics` context, which you can change if you need to...

Problem

How to calculate width of a `String` in pixels in Java? For e.g., I have a string say "Hello World!". What is its length in pixels, also considering its font family and size?

Original source

Related problems