Paint.breakText() counts glyphs, not characters

1.6k views Asked by At

One of our developers ran into an issue where Paint.breakText() (which says it counts "chars") is actually counting glyphs.

Imagine that you are wrapping just the one word "fit". It will fit on the line, so you expect breakText() to return 3. On some devices, it does; on others, the "fi" form a ligature, and breakText() returns 2. This cause you to draw

fi
t

... which is not what you want!

Is there either

  1. A flag to make breakText() count Java chars, not glyphs? Or
  2. A way to detect that "fi" will be treated as a single glyph?
2

There are 2 answers

0
Jon Shemitz On

This seems sort of sub-optimal, but the way we're dealing with it is to use paint.breakText("fit", true, 1000, null) == 2 as a bugExists flag, and then use measureText() to check the results.

1
Ruben Ferradás On

I found how to do it well here: Android: is Paint.breakText(...) inaccurate?

my code is:

on onCreate:

paintOfText.setSubpixelText(true);
breakTextNumber = paintOfText.breakText(textToBreak, true,
    maximumSizeOfText, null);

on render class:

if (breakTextNumber < textToBreak.length()) {
    while (textToBreak.charAt(breakTextNumber) != ' ') {
        breakTextNumber--;
    }
    myCanvas.drawText(textToBreak.substring(0, breakTextNumber),
            placeToDrawX, placeToDrawY, paintOfText);
    myCanvas.drawText(
            textToBreak.substring(breakTextNumber+1),
            placeToDrawX, placeToDrawY2,, paintOfText);
    }
}

This is just to split text in 2 lines, cutting the string with spaces. Hope it helps.