原理
布局完成后宙彪,根據(jù)當(dāng)前字體大小和已繪制的寬度與TextView的寬度的比例調(diào)整字體相應(yīng)的比例缘薛。
調(diào)整后字體大小 = view寬度 / 繪制寬度 * 當(dāng)前字體大小
public class ScaleTextView extends TextView {
public ScaleTextView(Context context) {
this(context, null, 0);
}
public ScaleTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ScaleTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {@Override public void onGlobalLayout() {
//測量字符串的長度
float measureWidth = getPaint().measureText(String.valueOf(getText()));
//得到TextView 的寬度
int width = getWidth() - getPaddingLeft() - getPaddingRight();
//當(dāng)前size大小
float textSize = getTextSize();
if (width < measureWidth) {
textSize = (width / measureWidth) * textSize;
}
//注意腻要,使用像素大小設(shè)置
setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
}
}