思路:在字体改变时,重新计算行数,和宽高
private void refitText(String text, int textWidth, int textHeight) {
if (textWidth > 0 && textHeight > 0) {
/**
* 当前的宽高
*/
int currentWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
int currentHeight = textHeight - this.getPaddingBottom() - this.getPaddingTop();
//by the line calculate allow displayWidth
int autoWidth = currentWidth;
float mult = 1f;
float add = 0;
if (Build.VERSION.SDK_INT > 16) {
mult = getLineSpacingMultiplier();
add = getLineSpacingExtra();
} else {
//the mult default is 1.0f,if you need change ,you can reflect invoke this field;
}
float trySize = maxTextSize;
mTextPaint.setTextSize(trySize);
int oldline = 1, newline = 1;
//计算最大宽高
while ((trySize > minTextSize)) {
//拿到一行字体所占的宽
int displayW = (int) mTextPaint.measureText(text);
//拿到一行字体所占高
int displaH = round(mTextPaint.getFontMetricsInt(null) * mult + add);
if (displayW < autoWidth) {
break;
}
//计算最大行数
newline = currentHeight / displaH;
//如果行数改变了,重新计算宽度
if (newline > oldline) {
oldline = newline;
autoWidth = currentWidth * newline;
continue;
}
//try more small TextSize
trySize -= 1;
if (trySize <= minTextSize) {
trySize = minTextSize;
break;
}
mTextPaint.setTextSize(trySize);
}
//setMultiLine
if (newline >= 2) {
this.setSingleLine(false);
this.setMaxLines(newline);
}
this.setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize);
}
}