grantland / android-autofittextview

A TextView that automatically resizes text to fit perfectly within its bounds.
Apache License 2.0
4.27k stars 688 forks source link

Text height is not considered #19

Closed jerryafr closed 9 years ago

jerryafr commented 10 years ago

Text height is not measured and considered. So, when a single line short text (like HELLO) with big textview width and small textview height is used, the size will be too big for the height.

The following method can be used to determine the height.

private int getTextHeight(CharSequence text, TextPaint paint, int targetWidth, float textSize) {
    TextPaint paintCopy = new TextPaint(paint);
    paintCopy.setTextSize(textSize);
    StaticLayout layout = new StaticLayout(text, paintCopy, (int)targetWidth, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0.0f, true);
    return layout.getHeight();
}

At the end of "void refitText()" method, using the following code would solve the problem:

        while(getTextHeight(text, mPaint, targetWidth, size) > targetHeight) {
            size--;
        }
       super.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
grantland commented 9 years ago

Merging into #5

KonradJanica commented 9 years ago

I implemented this option myself before finding it on here. The below is a slightly optimized version that scales the height using ratio instead. I think it would be a good idea to include a bool member (such as the mHelper.mEnabled bool) that would control height scaling in the library. (I can do this in some spare time if you like)

        int targetHeight = view.getHeight() - view.getPaddingTop() - view.getPaddingTop();
        if (targetHeight <= 0) {
            view.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
            return;
        }

        float textHeight = getTextHeight(text, paint, targetWidth, size);
        textHeight = getTextHeight(text, paint, targetWidth, size);
        float heightRatio = targetHeight / textHeight;
        float newSize = size * heightRatio;
        if (newSize < size) {
            size = newSize;
        }