项目中要用到闪烁字来标识一些重要的提醒以及醒目的文字等,这里Android并没有为我们提供一些组件,这里可以使用自定义的TextView,运用paint设置渐变渲染器LinearGradient来实现。
先看一下实现的效果,由于写的仓促就没有做动图了。。。就是一个蓝色的渐变:
先来看一下渐变渲染器的LinearGradient的API
构造方法
可以看到,需要传递的参数分别是沿着一条直线的梯度变化坐标点和梯度渐变的颜色数组。这里我们就可以为我们的paint设置LinearGradient来绘制这个控件。
实现代码:
如果控件要支持wrap_content的控件大小的时候,自定义控件的时候必须重写onMeasure()方法,去给出指定的大小。
<span style="font-size:18px;">public class SharderTextView extends TextView { //控件的宽 int mViewWidth; //平移量 int mTransLate; private TextPaint paint; private LinearGradient mlinearGradient; private Matrix matrix; public SharderTextView(Context context) { super(context); } public SharderTextView(Context context, AttributeSet attrs) { super(context, attrs); } public SharderTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(measureWidth(widthMeasureSpec),measureHigth(heightMeasureSpec)); } /** * 测量宽的方法 * @param measureSpec * @return */ private int measureWidth(int measureSpec){ int result = 0; int measureMode = MeasureSpec.getMode(measureSpec); int size = MeasureSpec.getSize(measureSpec); if(measureMode == MeasureSpec.EXACTLY) { result = size; }else{ result = 200; //当控件为warp_content时 if(measureMode ==MeasureSpec.AT_MOST) { result = Math.min(result,size); } } return result; } /** * 测量控件高度的方法 * @param measureSpec * @return */ private int measureHigth(int measureSpec) { int result = 0; int measureMode = MeasureSpec.getMode(measureSpec); int size = MeasureSpec.getSize(measureSpec); if(measureMode == MeasureSpec.EXACTLY) { result = size; }else{ result = 200; if(measureMode == MeasureSpec.AT_MOST) { result = Math.min(result,size); } } return result; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if(mViewWidth ==0) { mViewWidth = getMeasuredWidth(); } if(mViewWidth>0) { //获取绘制当前TextView的paint对象 paint = getPaint(); //创建渲染渐变器 mlinearGradient = new LinearGradient(0,0,mViewWidth,0,new int[]{Color.BLUE,0xffffffff,Color.BLUE},null, Shader.TileMode.CLAMP); paint.setShader(mlinearGradient); matrix = new Matrix(); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if(matrix!=null) { mTransLate+=mViewWidth/5; if(mTransLate>2*mViewWidth) { mTransLate = -mViewWidth; } matrix.setTranslate(mTransLate,0); mlinearGradient.setLocalMatrix(matrix); postInvalidateDelayed(100); } } } </span>