android-autofittextview自适应字体大小源码分析。

https://github.com/grantland/android-autofittextview。

用法:

<me.grantland.widget.AutofitTextView
    android:id="@+id/output_autofit"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/example"
    android:textSize="50sp"
    android:gravity="center"
    android:singleLine="true"
    autofit:minTextSize="8sp"
    />

mMaxTextSize = mTextSize;
mTextSize为xml中设置的字体大小。

if ((maxLines == 1 && paint.measureText(text, 0, text.length()) > targetWidth)
        || getLineCount(text, paint, size, targetWidth, displayMetrics) > maxLines) {
    size = getAutofitTextSize(text, paint, targetWidth, maxLines, low, high, precision,
            displayMetrics);
}

以单行为例:

maxLineWidth = paint.measureText(text, 0, text.length());

每次都要计算一行的宽度,和实际的宽度对比,来调整字体大小,是变大还是变小。

限制多行的例子:

要麻烦一些。第一步,先从行数上逼近。

layout = new StaticLayout(text, paint, (int)targetWidth, Layout.Alignment.ALIGN_NORMAL,
        1.0f, 0.0f, true);
lineCount = layout.getLineCount();

第二步,如果行数一样了,再逼近宽度。取所有行数最宽的作为比较对象。

for (int i = 0; i < lineCount; i++) {
    if (layout.getLineWidth(i) > maxLineWidth) {
        maxLineWidth = layout.getLineWidth(i);
    }
}

    原文作者:Android源码分析
    原文地址: https://blog.csdn.net/xiayu98020214/article/details/78120834
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞