这个是看了HongChengDarren的文章写的 点击打开链
/**
* Created by Cwm on 2018/3/6.
* 继承TextView可以省去很多的复写方法
*/
public class DiscolorText extends android.support.v7.widget.AppCompatTextView {
private int mChangeColor = Color.RED;
private int mNormalColor = Color.BLACK;
private Paint mChangePaint, mNormalPaint;
private float mProgress = 0.0f;
private Towards mTowards = Towards.Left_To_Righ;
//使用枚举设置朝向
public enum Towards {
Left_To_Righ, Righ_To_Left
}
public DiscolorText(Context context) {
this(context, null);
}
public DiscolorText(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public DiscolorText(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DiscolorText);
mChangeColor = typedArray.getColor(R.styleable.DiscolorText_changeColor, mChangeColor);
mNormalColor = typedArray.getColor(R.styleable.DiscolorText_normalColor, mNormalColor);
typedArray.recycle();
mChangePaint = initPaint(mChangeColor);
mNormalPaint = initPaint(mNormalColor);
}
//初始化画笔
private Paint initPaint(int color) {
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(color);
paint.setDither(true);//防抖动
paint.setTextSize(getTextSize());
return paint;
}
@Override
protected void onDraw(Canvas canvas) {
//继承TextView不能使用父类的onDraw方法,必须覆盖重写
int currentProgress = (int) (getWidth() * mProgress);
if (mTowards==Towards.Left_To_Righ){//从左到右
drawText(0,currentProgress,canvas,mChangePaint);//变色
drawText(currentProgress,getWidth(),canvas,mNormalPaint);//不变色
}else {
drawText(getWidth()-currentProgress,getWidth(),canvas,mChangePaint);//变色
drawText(0,getWidth()-currentProgress,canvas,mNormalPaint);//不变色
}
}
/**
* 绘制文字
* @param start
* @param end
* @param canvas
* @param paint
*/
public void drawText(int start,int end,Canvas canvas,Paint paint){
canvas.save();
canvas.clipRect(new RectF(start, 0, end, getHeight()));
String text = getText().toString().trim();
Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
int dx = getWidth() / 2 - bounds.width() / 2;
Paint.FontMetricsInt fontMetricsInt = mNormalPaint.getFontMetricsInt();
int dy = (fontMetricsInt.bottom - fontMetricsInt.top) / 2 - fontMetricsInt.bottom;
int baseLine = getHeight() / 2 + dy;
canvas.drawText(text, dx, baseLine, paint);
canvas.restore();
}
//设置颜色改变进度
public void setProgress(float progress) {
this.mProgress = progress;
invalidate();
}
//设置朝向
public void setTowards(Towards towards) {
this.mTowards = towards;
}
//设置颜色
public void setChangeColor(int changeColor) {
this.mChangeColor = changeColor;
}
public void setNormalColor(int normalColor) {
this.mNormalColor = normalColor;
}
直接在xml使用即可 可自行添加方法和自定义属性