rototor/pdfbox-graphics2d

PdfBoxGraphics2DFontTextDrawer.getFontMetrics always floors the width

MarkusDLN opened this issue · 3 comments

I ran into an issue with the FontMetrics provided by the PdfBoxGraphics2DFontTextDrawer when using it for the method SwingUtilities.layoutCompoundLabel. The method tries to shorten the given text if necessary and add three dots at the end (...) to indicate that the original string was longer. To do this the method goes character by character until the available width is reached.
The issue now is that the FontMetrics always floors the width so that the sum of the width of the individual characters will always be (significantly) lower than the actual width of the string represented by these characters (for non monospaced fonts).
I think this should be rounded (like sun.font.FontDesignMetrics) by adding 0.5f before casting to an int.

I made a simple test case for this. As documented on the stringWidth() method, this is always off. I.e. the sum of all single char widths will never be the width of the complete string.

This is how it looks like without the rounding like FontDesignMetrics:
image

And this is how it looks like with the rounding:
image

You can see that the first case underestimates the string width, the second ("fixed") version overestimates the stringWidth.

So relying on this is broken in any way. But with this "fix" it is now broken the same way as in the JDK. So its now more consistent.

I just release version 0.37 with this fix.

Thank you for your quick response and the new release. Much appreciated.