package com.sikkha.skline.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
/**
* ================================================
* 作 者:Vip
* 版 本:1.0
* 创建日期: 2018/4/3
* 描 述:自动缩放的文本
* 修订历史:
* ================================================
*/
@SuppressLint("AppCompatCustomView")
public class AutoScaleTextView extends TextView {
private static float DEFAULT_MIN_TEXT_SIZE = 0;
private static float DEFAULT_MAX_TEXT_SIZE = 48;
private Paint testPaint;
private float minTextSize;
private float maxTextSize;
public AutoScaleTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initialise();
}
private void initialise() {
testPaint = new Paint();
testPaint.set(this.getPaint());
maxTextSize = this.getTextSize();
if (maxTextSize <= DEFAULT_MIN_TEXT_SIZE) {
maxTextSize = DEFAULT_MAX_TEXT_SIZE;
}
minTextSize = DEFAULT_MIN_TEXT_SIZE;
}
private void refitText(String text, int textWidth) {
if (textWidth > 0) {
int availableWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
float trySize = maxTextSize;
testPaint.setTextSize(trySize);
while ((trySize > minTextSize) && (testPaint.measureText(text) > availableWidth)) {
trySize -= 1;
if (trySize <= minTextSize) {
trySize = minTextSize;
break;
}
testPaint.setTextSize(trySize);
}
//TypedValue.COMPLEX_UNIT_PX不可少,将单位设置为像素
this.setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize);
}
}
@Override
protected void onTextChanged(CharSequence text, int start, int before, int after) {
super.onTextChanged(text, start, before, after);
refitText(text.toString(), this.getWidth());
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
if (w != oldw) {
refitText(this.getText().toString(), w);
}
}
}
工具类:自定义缩放的文本控件
最新推荐文章于 2021-12-13 10:04:46 发布