要完成这样的效果.
1.1 一个字体两种颜色
1.1.1两种字体,需要定义自定义属性
//获取TypedArray
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ColorTrackTextView);
mOriginalColor = typedArray.getColor(R.styleable.ColorTrackTextView_originalColor, mOriginalColor);
mChangeColor = typedArray.getColor(R.styleable.ColorTrackTextView_changeColor, mChangeColor);
//回收
typedArray.recycle();
1.1.2 两种字体,两种画笔
mOriginalPaint = getPaint(mOriginalColor);
mChangePaint = getPaint(mChangeColor);
private Paint getPaint(int color) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(color);
paint.setTextSize(getTextSize());
//防抖动
paint.setDither(true);
return paint;
}
1.1.3 只绘制一部分区域的字体
用到canvas.clipRect(rect);来裁剪区域
private void drawText(Canvas canvas, int start, int end, Paint paint) {
canvas.save();
//区域
Rect rect = new Rect(start, 0, end, getHeight());
//裁剪区域,只允许在这个区域绘制内容
canvas.clipRect(rect);
//获取文字
String text = getText().toString();
//字体宽度
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
int x = getWidth() / 2 - bounds.width() / 2;
//基线
//指定中间位置,求基线
Paint.FontMetricsInt fontMetricsInt = paint.getFontMetricsInt();
int baseLine = getHeight() / 2 + (fontMetricsInt.bottom - fontMetricsInt.top) / 2 - fontMetricsInt.bottom;
canvas.drawText(text, x, baseLine, paint);
canvas.restore();
}
1.1.4 提供公共方法
提供进度的公共方法.
public void setCurrentProgress(double currentProgress) {
this.mCurrentProgress = currentProgress;
invalidate();
}
根据进度计算中间值,根据中间值绘制变色字体
// 根据进度把中间值算出来
int middle = (int) (mCurrentProgress * getWidth());
// 绘制变色
drawText(canvas, 0, middle, mChangePaint);
drawText(canvas, middle, getWidth(),mOriginalPaint);
效果
结合ViewPager见完整代码.
完整代码:colortracktextview