1. 程式人生 > >android 使用LinearGradient實現手機開機文字閃爍效果

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:顏色漸變百分比值

一張圖說明問題:


現在要實現我們今天要講的效果,程式碼如下:

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); } }
效果:


ok!