作者:懒得张开眼睛看你 | 来源:互联网 | 2023-08-16 07:55
一、应用背景:在工作中遇到凭证界面展示金额的时候,用原生TextView数字之间间距太小,于是想到自定控件来实现。二、具体实现:publicclassMoneyTextViewextendsV
一、应用背景:
在工作中遇到凭证界面展示金额的时候,用原生TextView数字之间间距太小,于是想到自定控件来实现。
二、具体实现:
public class MoneyTextView extends View {
private float letterSpacing;//字符间距
private Paint letterPaint;//画笔
private CharSequence content = "13200000081";//金额,最多11位数
private Context context;
public MoneyTextView(Context context) {
super(context);
this.context = context;
init();
}
public MoneyTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
public void setText(CharSequence text) {
content = text;
invalidate();
}
private void init() {
Paint mPaint = new Paint();
mPaint.setStrokeWidth(3);
mPaint.setTextSize(dip2px(14));
mPaint.setAntiAlias(true);
mPaint.setColor(Color.RED);
mPaint.setTextAlign(Paint.Align.LEFT);
letterPaint = mPaint;
}
public MoneyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.context = context;
init();
}
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public int dip2px(float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public int px2dip(float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(content != null ) {
letterSpacing = (float) (getMeasuredWidth()/11.0);//项目需要固定十一份大小,可根据需要调整
Log.e("onDraw",letterSpacing+","+getMeasuredWidth());
for (int i = content.length() - 1, j = 0; i >= 0; i--) {
Rect bounds = new Rect();
String str = String.valueOf(content.charAt(i));
Log.e("onDraw", str + "");
letterPaint.getTextBounds(str, 0, str.length(), bounds);
Paint.FontMetricsInt fOntMetrics= letterPaint.getFontMetricsInt();
int baseline = (getMeasuredHeight() - fontMetrics.bottom + fontMetrics.top) / 2 - fontMetrics.top;
canvas.drawText(str, getMeasuredWidth() - bounds.width() - (letterSpacing/2 - bounds.width()/2 )- j++ * letterSpacing, baseline, letterPaint);
}
}
}
}
三、效果如下:
MoneyTextView tv = (MoneyTextView) findViewById(R.id.moneyTv);
tv.setText("15000320");
参考文章:http://blog.csdn.net/lovexieyuan520/article/details/43153275