Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which API returns the right font width in Java?

Which Font API of Java returns the right width? We use currently

font.getStringBounds( "the string", frc ).getWidth();

This return the right values on images and display. But it is wrong on printing with Java SE 6. With Java 7 all is correct. The difference is very small. But we lost one "i" at end of a line. We receive on printing exact the same values. But the text need more space on a printing graphics.

We use anti alias and fractional metrics.

I know there are different API. But what is the recommended API?

like image 501
Horcrux7 Avatar asked Sep 20 '26 19:09

Horcrux7


1 Answers

Do you have a Graphics object to the printer? What does in that case happen if you test this code? It's what I'm using to measure width:

/*
Graphics2D g
Font currentFont
String stringToMeasure
*/
FontMetrics currentFontMetrics = g.getFontMetrics(currentFont);
Rectangle2D stringBounds = currentFontMetrics.getStringBounds(stringToMeasure, g);
double width = stringBounds.getWidth();
like image 199
Kaj Avatar answered Sep 23 '26 09:09

Kaj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!