Auto Scale TextView Text to Fit within Bounds

后端 未结 30 2872
囚心锁ツ
囚心锁ツ 2020-11-21 05:49

I\'m looking for an optimal way to resize wrapping text in a TextView so that it will fit within its getHeight and getWidth bounds. I\'m not simply looking for

30条回答
  •  别跟我提以往
    2020-11-21 06:16

    I found the following to work nicely for me. It doesn't loop and accounts for both height and width. Note that it is important to specify the PX unit when calling setTextSize on the view.

    Paint paint = adjustTextSize(getPaint(), numChars, maxWidth, maxHeight);
    setTextSize(TypedValue.COMPLEX_UNIT_PX,paint.getTextSize());
    

    Here is the routine I use, passing in the getPaint() from the view. A 10 character string with a 'wide' character is used to estimate the width independent from the actual string.

    private static final String text10="OOOOOOOOOO";
    public static Paint adjustTextSize(Paint paint, int numCharacters, int widthPixels, int heightPixels) {
        float width = paint.measureText(text10)*numCharacters/text10.length();
        float newSize = (int)((widthPixels/width)*paint.getTextSize());
        paint.setTextSize(newSize);
    
        // remeasure with font size near our desired result
        width = paint.measureText(text10)*numCharacters/text10.length();
        newSize = (int)((widthPixels/width)*paint.getTextSize());
        paint.setTextSize(newSize);
    
        // Check height constraints
        FontMetricsInt metrics = paint.getFontMetricsInt();
        float textHeight = metrics.descent-metrics.ascent;
        if (textHeight > heightPixels) {
            newSize = (int)(newSize * (heightPixels/textHeight));
            paint.setTextSize(newSize);
        }
    
        return paint;
    }
    

提交回复
热议问题