您的位置:首页 > 移动开发 > Android开发

LinearGradient和Matrix实现动态的文字闪烁效果

2016-07-05 16:33 501 查看

先看下效果



首先先看下
LinearGradient
的实现

Android提供的Shader类主要是渲染图像以及一些几何图形。
Shader有几个直接子类:


BitmapShader : 主要用来渲染图像

LinearGradient :用来进行线性渲染

RadialGradient : 用来进行环形渲染

SweepGradient : 扫描渐变—围绕一个中心点扫描渐变就像电影里那种雷达扫描,用来梯度渲染。

ComposeShader : 组合渲染,可以和其他几个子类组合起来使用。

有两种不同的实现方法

简单的一种

Paint mPaint=new Paint();
LinearGradient lg = new LinearGradient(float x0,float y0,float x1,float y1,int color0,int color1,Shader.TileMode tile);
mPaint.setShader(lg);


x0 渐变起点坐标x位置

y0 渐变起点坐标y位置

x1 渐变起终点坐标x位置

y1 渐变起终点坐标y位置

color0 渐变颜色起始色

color1 渐变颜色终止色

Shader.TileMode tile 平铺方式

复杂的一种

public LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions, Shader.TileMode tile)


x0 渐变起点坐标x位置

y0 渐变起点坐标y位置

x1 渐变起终点坐标x位置

y1 渐变起终点坐标y位置

colors 渐变颜色数组

positions是定义每个颜色处于的渐变相对位置,这个参数可以为null,如果为null表示所有的颜色按顺序均匀的分布

Shader.TileMode tile 平铺方式

下面看下代码

其中最关键的是使用`getPaint()`方法获取当前绘制的TextVIew的Paint对象,并给这个Paint对象设置原生TextView没有的LinearGradient属性,最后在onDraw()中,通过矩阵的方式来不断平移渐变效果,从而在绘制文字时,产生闪烁效果,


里面的字体只循环闪烁三次

public class ShineTextView extends TextView {

private LinearGradient mLinearGradient;
private Matrix mGradientMatrix;
private Paint mPaint;
private int mViewWidth = 0;
private int mViewHeight = 0;
private int mTranslate = 0;
int i =0;
public ShineTextView(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) {
mViewWidth = getMeasuredWidth();
mViewHeight = getMeasuredHeight();
if (mViewWidth > 0) {
mPaint = getPaint();
mLinearGradient = new LinearGradient(
0,
0,
mViewWidth,
mViewHeight,
new int[]{
Color.BLUE, 0xffffffff,
Color.BLUE},
null,
Shader.TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
mGradientMatrix = new Matrix();
}
}
}

private static final String Tag = "MSH";
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);

if (mGradientMatrix != null) {
mTranslate += mViewWidth / 5;
if (mTranslate > 2 * mViewWidth) {
mTranslate = -mViewWidth;
i++;
Log.d(Tag,"第  "+i+"   次");
if (i==3)
{
return;
}
}
mGradientMatrix.setTranslate(mTranslate, 0);
mLinearGradient.setLocalMatrix(mGradientMatrix);
postInvalidateDelayed(300);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android