熟话说,没图我说个XX,所以我这儿配备一张动态图片:
Shader.TileMode有3种参数可供选择,分别为CLAMP、REPEAT和MIRROR:
CLAMP的作用:是如果渲染器超出原始边界范围,则会复制边缘颜色对超出范围的区域进行着色
REPEAT的作用是:在横向和纵向上以平铺的形式重复渲染位图
MIRROR的作用是:在横向和纵向上以镜像的方式重复渲染位图
注意:通常,参数positions设为null,表示颜色数组以斜坡线的形式均匀分布。
public class GradientTextView extends TextView { private LinearGradient mLinearGradient; private Matrix mGradientMatrix; private Paint mPaint; private int mViewWidth = 0; private int mTranslate = 0; private boolean mAnimating = true; public GradientTextView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (mViewWidth == 0) { //getWidth得到是某个view的实际尺寸. //getMeasuredWidth是得到某view想要在parent view里面占的大小. mViewWidth = getMeasuredWidth(); if (mViewWidth > 0) { mPaint = getPaint(); //线性渐变 mLinearGradient = new LinearGradient(-mViewWidth, 0, 0, 0, new int[] { 0x33ffffff, 0xffffffff, 0x33ffffff }, new float[] { 0, 0.5f, 1 }, Shader.TileMode.CLAMP); mPaint.setShader(mLinearGradient); mGradientMatrix = new Matrix(); } } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mAnimating && mGradientMatrix != null) { mTranslate += mViewWidth / 10; if (mTranslate > 2 * mViewWidth) { mTranslate = -mViewWidth; } mGradientMatrix.setTranslate(mTranslate, 0); mLinearGradient.setLocalMatrix(mGradientMatrix); //50ms刷新一次 postInvalidateDelayed(50); } } }