Android闪动的文字效果

来源:互联网 发布:java redis 安装配置 编辑:程序博客网 时间:2024/04/29 17:56

方法:

自定义一个View,View继承TextView,使用LinearGradient渐染实现文字的闪动效果。

设置渐染的颜色:

@Overrideprotected void onSizeChanged(int w, int h, int oldw, int oldh) {super.onSizeChanged(w, h, oldw, oldh);if (mViewWidth == 0) {mViewWidth = getMeasuredWidth();if (mViewWidth > 0) {mPaint = getPaint();mLinearGradient = new LinearGradient(-mViewWidth, 0, 0, 0,new int[] { Color.RED, Color.BLUE, Color.YELLOW },null, Shader.TileMode.CLAMP);mPaint.setShader(mLinearGradient);mGradientMatrix = new Matrix();}}}
getMeasuredWidth();获取TextView的原始测量宽度;
getPaint():获取当前TextView绘制的Paint对象;
LinearGradient(线性渐变):LinearGradient(float x0, float y0, float x1, float y1,int colors[], float positions[], TileMode tile),x0、x1分别表示x轴移动起点、终点,y0、y1分别表示代表y轴移动起点、终点,colors[]用来存放渐变的颜色。positions[]用来存放与colors[]对应的颜色的相对分布位置,null表示所有的颜色按顺序均匀的分布。tile:渲染器平铺模式,共有三种模式:android.graphics.Shader.TileMode.CLAMP(API解释:replicate the edge color if the shader draws outside of its original bounds,如果着色绘制超出它的原始边界复制边缘颜色)、android.graphics.Shader.TileMode.REPEAT(API解释:repeat the shader's image horizontally and vertically,横向和纵向的重复渲染图片,平铺)、android.graphics.Shader.TileMode.MIRROR(API解释:repeat the shader's image horizontally and vertically, alternating  mirror images so that adjacent images always seam,横向和纵向的重复渲染器图片,以镜像方式平铺。)。

绘制闪烁平移量

这个过程类似火车过隧道,行驶速度为mViewWidth / 5,当mTranslate > 2 * mViewWidth时代表整列火车都已经离开隧道,这时候赋值-mViewWidth,相当于把火车恢复到过隧道之前的位置重新过隧道,-mViewWidth代表的是火车尾所在的位置。

@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);if (mGradientMatrix != null) {mTranslate += mViewWidth / 5;if (mTranslate > 2 * mViewWidth) {mTranslate = -mViewWidth;}mGradientMatrix.setTranslate(mTranslate, 0);//设置平移量mLinearGradient.setLocalMatrix(mGradientMatrix);//设置着色矩阵postInvalidateDelayed(100);//延迟100ms刷新界面}}


                                             
0 0