javaawtjava-2d

How to include trailing space in text measurements using TextLayout?


I am using the java.awt.font.TextLayout class to measure the bounds of a text string. In this measurement I need to include any trailing whitespace. However it seems that by default, TextLayout ignores any trailing whitespace when computing text bounds. Here's an example:

import java.awt.geom.*;
import java.awt.font.*;
import java.text.*;

public class scratch
{
    public static double measureTextWidth(String text)
    {
        AttributedString astring = new AttributedString(text);
        AffineTransform at = new AffineTransform();
        FontRenderContext frc = new FontRenderContext(at, true, true);
        TextLayout layout = new TextLayout(astring.getIterator(), frc);
        return layout.getBounds().getWidth();
    }

    public static void main(String args[])
    {
        System.out.println(measureTextWidth("sometext"));
        System.out.println(measureTextWidth("sometext    "));
    }
}

This code returns the same width for both strings, ignoring the trailing whitespace for the second one.

Is there any way to have TextLayout consider trailing whitespace when computing the width of the supplied text string?


Solution

  • layout.getBounds() returns a bounding box around actual content, so it’s not only not including trailing white-space but also not including leading white-space and even not including empty space within the actual character graphics of the first and last non-space character, at least as long as you are ignoring the x value of the box.

    Even worse, it’s documentation says:

    Due to rasterization effects, this bounds might not enclose all of the pixels rendered by the TextLayout.

    What you most probably want, is to get the advance of the TextLayout, so replace layout.getBounds().getWidth() with layout.getAdvance().