思路:在字體改變時坊萝,重新計(jì)算行數(shù),和寬高
private void refitText(String text, int textWidth, int textHeight) {
if (textWidth > 0 && textHeight > 0) {
/**
* 當(dāng)前的寬高
*/
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;
//計(jì)算最大寬高
while ((trySize > minTextSize)) {
//拿到一行字體所占的寬
int displayW = (int) mTextPaint.measureText(text);
//拿到一行字體所占高
int displaH = round(mTextPaint.getFontMetricsInt(null) * mult + add);
if (displayW < autoWidth) {
break;
}
//計(jì)算最大行數(shù)
newline = currentHeight / displaH;
//如果行數(shù)改變了酷勺,重新計(jì)算寬度
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);
}
}