一个加了线性变换渲染器shader的自定义TextView

/**
 * 一个加了线性变换渲染器shader的自定义TextView
 * mLinearGradient加了平移效果
 */
public class GreateTextView extends AppCompatTextView {
    private Paint mPaint1;
    private Paint mPaint2;
    private int mViewWith;
    private LinearGradient mLinearGradient;
    private Paint paint;
    private Matrix matrix;
    private int mTranslate;


    public GreateTextView(Context context) {
        this(context, null);
    }

    public GreateTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GreateTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint1 = new Paint();
        mPaint1.setColor(getResources().getColor(R.color.role_yellow_gray));
        mPaint1.setStyle(Paint.Style.FILL);
        mPaint2 = new Paint();
        mPaint2.setColor(getResources().getColor(R.color.red));
        mPaint2.setStyle(Paint.Style.FILL);

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(measure(widthMeasureSpec), measure(heightMeasureSpec));

    }

    private int measure(int measureSpec) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            result = 200;
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }


    //layout的时候调用的方法,组件大小改变的时候回调
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if (mViewWith == 0) {
            mViewWith = getMeasuredWidth();

            if (mViewWith > 0) {
                paint = getPaint();
                mLinearGradient = new LinearGradient(0, 0, mViewWith, 0, new int[]{Color.BLUE, 0xffffffff,
                        Color.BLUE}, null, Shader.TileMode.CLAMP);
                paint.setShader(mLinearGradient);
                matrix = new Matrix();
            }
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint1);
        canvas.drawRect(10, 10, getMeasuredWidth() - 10, getMeasuredHeight() - 10, mPaint2);
        super.onDraw(canvas);

        if (matrix != null) {
            mTranslate += mViewWith / 5;
            if (mTranslate > 2 * mViewWith) {
                mTranslate = -mViewWith;
            }
            matrix.setTranslate(mTranslate, 0);
            mLinearGradient.setLocalMatrix(matrix);
            postInvalidateDelayed(100);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/hpp_1225/article/details/88780619