自定义TextView

这里写图片描述

这里写图片描述

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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值