public class MyTextView extends TextView {
Paint mpaint1;
Paint mpaint2;
Paint paint;
private int mwidth;
private LinearGradient gradient;
private Matrix matrix;
private int speedX;
private int i = 0;
public MyTextView(Context context) {
super(context);
this.init();
}
public MyTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
this.init();
}
public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.init();
}
private void init(){
this.mpaint1 = new Paint();
this.mpaint1.setColor(getResources().getColor(android.R.color.holo_blue_bright));
this.mpaint1.setStyle(Paint.Style.FILL);
this.mpaint2 = new Paint();
this.mpaint2.setColor(Color.YELLOW);
this.mpaint2.setStyle(Paint.Style.FILL);
this.speedX = 0;
this.mwidth = 0;
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
paint = getPaint();
mwidth = getMeasuredWidth();
//线性变换
this.gradient = new LinearGradient(0 ,
0 ,
mwidth ,
0,
new int[]{Color.BLUE , Color.RED, Color.GREEN},
null,
Shader.TileMode.CLAMP);
paint.setShader(this.gradient);
this.matrix = new Matrix();
}
@Override
protected void onDraw(Canvas canvas) {
//这段代码对应第一个图
canvas.drawRect(0
,0
,this.getMeasuredWidth()
,this.getMeasuredHeight()
,this.mpaint1);
canvas.drawRect(10 ,
10 ,
this.getMeasuredWidth() - 10,
this.getMeasuredHeight() - 10 ,
this.mpaint2);
canvas.save();
canvas.translate(0 , 10);
super.onDraw(canvas);
canvas.restore();
//
}
}
//这段代码对应第二个动态图
if(this.matrix != null){
speedX += mwidth / 5;
if(speedX > 2 * mwidth)
speedX = -mwidth;
this.matrix.setTranslate(speedX , 0);
this.gradient.setLocalMatrix(matrix);
//每个10ms重新调用onDraw 话界面
this.postInvalidateDelayed(10);
}