android 使用LinearGradient实现手机开机文字闪烁效果

LinearGradient:线性渐变意思,这个也是继承了Shader类,先看下它的构造函数:

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

对构造函数进行简单的说明:

x0:起点x轴坐标

y0:起点y轴坐标

x1:终点x轴坐标

y1:终点y轴坐标

colors:颜色渐变值,这个和后面的positions值是对应的,

positions:颜色渐变百分比值

一张图说明问题:

android 使用LinearGradient实现手机开机文字闪烁效果_第1张图片

现在要实现我们今天要讲的效果,代码如下:

package com.bitmapshaderdemo;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.View;
/**
 * Created by admin on 2016/11/28.
 */
public class TextFlickerView extends View {
    private LinearGradient linearGradient;
    private String text = "今天杭州天气真好";
    private Paint paint;
    private float strWidth;
    private Matrix matrix;
    private float translateX;
    private int signleTextWidth;
    private int count = 1;//一次性跑多少个文字的个数
    public TextFlickerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }
    private void init() {
        matrix = new Matrix();
        paint = new Paint();
        paint.setTextSize(30);
        paint.setColor(Color.RED);
        /**
         * (float x0, float y0, float x1, float y1, int[] colors, float[] positions, android.graphics.Shader.TileMode tile)
         */
        strWidth =  paint.measureText(text);
        signleTextWidth=(int) (count*strWidth/text.length());//计算一个文字的宽度
        linearGradient = new LinearGradient(-signleTextWidth, 0, 0, 0, new int[]{0x22ffffff,0xffffffff,0x22ffffff}, new float[]{0,0.5f,1}, Shader.TileMode.CLAMP);//边缘融合
        paint.setShader(linearGradient);
    }
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawText(text,0,100,paint);
        translateX += signleTextWidth;//每次平移一个文字的宽度
        if(translateX>=strWidth){
            signleTextWidth = -signleTextWidth;
        }
        if(translateX==0){
            signleTextWidth = -signleTextWidth;
        }
        //实现平移一个文字的宽度
        matrix.setTranslate(translateX, 0);
        linearGradient.setLocalMatrix(matrix);
        postInvalidateDelayed(100);
    }
}
效果:

android 使用LinearGradient实现手机开机文字闪烁效果_第2张图片

ok!


你可能感兴趣的:(自定义控件)