Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String length in pixels in Java

Is there a way to calculate the length of a string in pixels, given a certain java.awt.Font object, that does not use any GUI components?

like image 690
APerson Avatar asked Nov 12 '12 14:11

APerson


2 Answers

that does not use any GUI components?

It depends on what you mean here. I'm assuming you mean you want to do it without receiving a HeadlessException.

The best way is with a BufferedImage. AFAIK, this won't throw a HeadlessException:

Font font = ... ;
BufferedImage img = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
FontMetrics fm = img.getGraphics().getFontMetrics(font);
int width = fm.stringWidth("Your string");

Other than using something like this, I don't think you can. You need a graphics context in order to create a FontMetrics and give you font size information.

like image 197
Brian Avatar answered Sep 19 '22 13:09

Brian


You can use the Graphics2D object to get the font bounds (including the width):

Graphics2D g2d = ...
Font font = ...
Rectangle2D f = font.getStringBounds("hello world!", g2d.getFontRenderContext());

But that depends on how you will get the Graphics2D object (for example from an Image).

like image 34
dacwe Avatar answered Sep 20 '22 13:09

dacwe