0

I've read all the existing questions I could find and have tried it both ways.

FontMetrics fm = g.getFontMetrics();
FontRenderContext frc = g.getFontRenderContext();
Rectangle2D rect = font.getStringBounds(line,frc);
int width = (int)rect.getWidth();

and also

int width = fm.stringWidth(line);

Neither are giving me the correct number of pixels. As an example...the word 'ELLIS' in a particular font and size is actually 58 pixels wide. Both of those methods tell me that it's 42 wide.

Its black font on a white field, so I'm considering re arranging my entire code so I can loop through a line of the BufferedImage and count the distance between the first and last black pixel. This would at least get me a lot closer.

There has to be a simpler way to do this though.

Appreciate any help.

  • 1
    Could you include a [minimal example](https://stackoverflow.com/help/mcve) which shows the difference in the widths? – cbr Jan 12 '18 at 16:59
  • What about using [getFontMetrics](https://stackoverflow.com/a/258499/5475891)? – phflack Jan 12 '18 at 17:01
  • phflack - I'm using that, I edited my snippet to include that now. – 736f5f6163636f756e74 Jan 12 '18 at 17:10
  • cubrr - I'm only finding the correct width by measuring it with the line tool in paint after I draw the string and write the file. Is that what you mean? My code outputs a width of 42 no matter what I do. – 736f5f6163636f756e74 Jan 12 '18 at 17:11
  • You say you're using a custom font, shouldn't you be using [`Graphics.getFontMetrics(Font)`](https://docs.oracle.com/javase/8/docs/api/java/awt/Graphics.html#getFontMetrics-java.awt.Font-)? Or have you set the font above that? – phflack Jan 12 '18 at 17:14
  • Kind of. For trying to debug right now, I'm just using Arial. Though I do have some custom fonts that will be getting used later. The reason I need the width is so that I can align the text on the right side of my graphic. The end of the word ending 20 pixels from the right every time. It aligns perfectly on the left (20 pixels in), custom fonts included, but on the right and centered, they are off. The bigger the font size the bigger the error. – 736f5f6163636f756e74 Jan 12 '18 at 17:20
  • I actually just found the text begins 23 pixels in from the left, which is close enough. Right and centered is not close enough. – 736f5f6163636f756e74 Jan 12 '18 at 17:22
  • Is `g.getFontMetrics()` getting you the metrics of your testing font, or of a different font? – phflack Jan 12 '18 at 17:27
  • Worth double checking but it should be the currently selected font. I set everything up in my listener using g2d.setFont and then pass g2d in to drawString(Graphics2D g, String text, int increment, String alignment,Font font) – 736f5f6163636f756e74 Jan 12 '18 at 17:39

0 Answers0