先看看效果图

1.自定义 View 的基本流程
- 创建 View Class
- 创建 attr 属性文件,确定属性
- View Class 绑定 attr 属性
- onMeasure 测量
- onDraw 绘制
1.1 创建 View Class
public class TrackView extends TextView {
public TrackView(Context context) {
this(context, null);
}
public TrackView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public TrackView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
1.2 创建 attr 属性
<declare-styleable name="TrackView">
<!--默认颜色-->
<attr name="originColor" format="color" />
<!--改变颜色-->
<attr name="changeColor" format="color" />
</declare-styleable>
1.3 绑定 attr 属性
private void initAttr(Context context, AttributeSet attrs) {
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TrackView);
//默认颜色
int originColor = array.getColor(R.styleable.TrackView_originColor, getTextColors().getDefaultColor());
//改变颜色
int changeColor = array.getColor(R.styleable.TrackView_changeColor, getTextColors().getDefaultColor());
//回收
array.recycle();
mOriginPaint = getPaintByColor(originColor);
mChangePaint = getPaintByColor(changeColor);
}
private Paint getPaintByColor(int color) {
Paint paint = new Paint();
//设置颜色
paint.setColor(color);
//抗锯齿
paint.setAntiAlias(true);
//防抖动
paint.setDither(true);
//字体大小
paint.setTextSize(getTextSize());
return paint;
}
1.4 onMeasure
因为继承自 TextVIew ,所以绘制方法交给父类,不做处理。
1.5 onDraw
protected void onDraw(Canvas canvas) {
//super.onDraw(canvas);
int middle = (int) (CurrentProgress * getWidth());
if (direction == Direction.LEFT_TO_RIGHT) {
drawText(canvas, mChangePaint, 0, middle);
drawText(canvas, mOriginPaint, middle, getWidth());
} else {
drawText(canvas, mChangePaint, getWidth() - middle, getWidth());
drawText(canvas, mOriginPaint, 0, getWidth() - middle);
}
}
private void drawText(Canvas canvas, Paint paint, int start, int end) {
canvas.save();
//获取文字
String text = getText().toString();
Rect rect = new Rect(start, 0, end, getHeight());
canvas.clipRect(rect);
paint.getTextBounds(text, 0, text.length(), rect);
int x = getWidth() / 2 - rect.width() / 2;
Paint.FontMetricsInt fontMetricsInt = paint.getFontMetricsInt();
int y = (fontMetricsInt.bottom - fontMetricsInt.top) / 2 - fontMetricsInt.bottom;
int baseline = getHeight() / 2 + y;
canvas.drawText(text, x, baseline, paint);
canvas.restore();
}
⚠️注意:1. super.onDraw(canvas) 一定要注释掉。 2.canvas的保存和回收。
网友评论