在开发过程中很多时候我们都会使用各种各样的效果,从而是界面的表现效果更加的漂亮。今天我们就来学习一下使用LinearGradient实现对TextView的渲染效果。下面我们就来看一下代码的实现。
public class ShineTextView extends TextView {
private LinearGradient mLinearGradient;
private Matrix mMatrix;
private Paint mPaint;
private int mViewWidth=0;
private int mTranslate=0;
public ShineTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ShineTextView(Context context) {
super(context);
}
public ShineTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if(mViewWidth==0){
mViewWidth=getMeasuredWidth();
mPaint=getPaint();
if(mViewWidth>0){
//参数一为渐变起初点坐标x位置,参数二为y轴位置,参数三和四分辨对应渐变终点,最后参数为平铺方式,这里设置为镜像
mLinearGradient=new LinearGradient(0,0,mViewWidth,0,Color.RED,Color.BLUE,Shader.TileMode.MIRROR);
mPaint.setShader(mLinearGradient);
mMatrix=new Matrix();
}
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mMatrix != null) {
mTranslate += mViewWidth / 5;
if (mTranslate > 2 * mViewWidth) {
mTranslate = -mViewWidth;
}
mMatrix.setTranslate(mTranslate, 0);
mLinearGradient.setLocalMatrix(mMatrix);
postInvalidateDelayed(100);
}
}
}