How to avoid the linebreak inside a word (Static Layout

Posted by Addev on Stack Overflow See other posts from Stack Overflow or by Addev
Published on 2012-12-14T23:00:33Z Indexed on 2012/12/14 23:03 UTC
Read the original article Hit count: 139

Filed under:
|
|
|

I'm trying to make a text as big as I can making it fit a Rect.

basically I use a StaticLayout for pre-calculate the text size and make it fit the Rect's height:

// Since the width is fixed for the StaticLayout it should only fit the height
while (currentHeight>Rect.getHeight()){
    size-=2;
}
textPaint.setTextSize(size);

The problem is that if the Rect is very high, the exit condition is reached but breaking the words (see the capture). Is there a way for avoid this?

Goal:

enter image description here

Actual:

enter image description here

Current code:

            textSize=MAX_TEXT_SIZE
    do {
        if (textSize < mMinTextSize) {
            Log.i(TAG, "Min reached");
            textSize = mMinTextSize;
            textPaint.setTextSize(textSize);
            fits = true;
        } else {
            textPaint.setTextSize(textSize);
            StaticLayout layout = new StaticLayout(text, textPaint, targetWidth, Alignment.ALIGN_NORMAL, 1.0,
                    0, true);
            layout.draw(canvas);
            float heightRatio= (float) layout.getHeight() / (float) targetHeight;
            boolean fitsHeight = heightRatio<= 1f;
            if (fitsHeight) {
                fits = true;
            } else {
                textSize -= 2;
            }
        }
        Log.i(TAG, "textSize=" + textSize + " fits=" + fits);

    } while (!fits);

thanks

© Stack Overflow or respective owner

Related posts about java

Related posts about android