public class PlayText extends android.support.v7.widget.AppCompatTextView {
private Paint mPaint;
private int mWidth;
private LinearGradient mLinearGradient;
private Matrix mMatrix;
private int mTranslate;
public PlayText(Context context) {
this(context,null);
}
public PlayText(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = getMeasuredWidth();
if (mWidth == 0 ){
mWidth = getMeasuredWidth();
}
if (mWidth > 0 ){
mPaint = getPaint();
//参数一为渐变起初点坐标x位置,参数二为y轴位置,参数三和四分辨对应渐变终点,参数五是参与渐变效果的颜色集合,参数六是是定义每个颜色处于的渐变相对位置,最后参数为平铺方式,这里设置为镜像
mLinearGradient = new LinearGradient(0,0,mWidth,0,new int[]{
Color.BLUE,0xffffffff,Color.RED,Color.GREEN
},null, Shader.TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
mMatrix = new Matrix();
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mMatrix != null) {
mTranslate += mWidth/5;
if (mTranslate > 2*mWidth){
mTranslate = -mWidth;
}
mMatrix.setTranslate(mTranslate,0);
mLinearGradient.setLocalMatrix(mMatrix);
postInvalidateDelayed(100);
}
}
}