android 根据TextView宽度 自动缩小字体大小 以适应其宽度
16lz
2021-01-23
package
cc.coin.view;
import
android.content.Context;
import
android.graphics.Canvas;
import
android.graphics.Paint;
import
android.graphics.Rect;
import
android.util.AttributeSet;
import
android.util.TypedValue;
import
android.widget.TextView;
/**
* 可根据字符串所占的长度(非字符串长度)自动缩小字体大小, 以适应显示区域的宽度
*
* @author sheng
*
*/
public
class
CustomTextView
extends
TextView {
// Attributes
private
Paint testPaint;
private
float
cTextSize;
public
CustomTextView (Context context, AttributeSet attrs) {
super
(context, attrs);
}
/**
* Re size the font so the specified text fits in the text box * assuming
* the text box is the specified width.
* 在此方法中学习到:getTextSize返回值是以像素(px)为单位的,而setTextSize()是以sp为单位的,
* 因此要这样设置setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
*/
private
void
refitText(String text,
int
textWidth) {
if
(textWidth >
0
) {
testPaint =
new
Paint();
testPaint.set(
this
.getPaint());
//获得当前TextView的有效宽度
int
availableWidth = textWidth -
this
.getPaddingLeft()
-
this
.getPaddingRight();
float
[] widths =
new
float
[text.length()];
Rect rect =
new
Rect();
testPaint.getTextBounds(text,
0
, text.length(), rect);
//所有字符串所占像素宽度
int
textWidths = rect.width();
cTextSize =
this
.getTextSize();
//这个返回的单位为px
while
(textWidths > availableWidth){
cTextSize = cTextSize -
1
;
testPaint.setTextSize(cTextSize);
//这里传入的单位是px
textWidths = testPaint.getTextWidths(text, widths);
}
this
.setTextSize(TypedValue.COMPLEX_UNIT_PX, cTextSize);
//这里制定传入的单位是px
}
};
@Override
protected
void
onDraw(Canvas canvas) {
super
.onDraw(canvas);
refitText(getText().toString(),
this
.getWidth());
}
}
更多相关文章
- android字符串 优化(一)
- android 获取屏幕高度和宽度
- Android中base64加密后的字符串带有“\n”导致出错的问题解决
- %1$s %1$d Android string (java & Android 格式化字符串)
- Android中字符串的拆分-split
- Android 获取屏幕高宽度,密度,通知栏高度,截图等常用方法
- android之4.0控件switch自定义开关滑块、滑块轨道和宽度
- iphone/android比较学习之──图片、文件、字符串
- 引用 Android上dip、dp、px、sp等单位说明