android 使用LinearGradient進行字型漸層的效果
LinearGradient也稱作線性渲染,LinearGradient的作用是實現某一地區內顏色的線性漸層效果 它有兩個建構函式 public LinearGradient(float x0, float y0, float x1, float y1, int color0, int color1, Shader.TileMode tile) 其中,參數x0表示漸層的起始點x座標;參數y0表示漸層的起始點y座標;參數x1表示漸層的終點x座標;參數y1表示漸層的終點y座標 ;color0表示漸層開始顏色;color1表示漸層結束顏色;參數tile表示平鋪方式。 Shader.TileMode有3種參數可供選擇,分別為CLAMP、REPEAT和MIRROR: CLAMP的作用是如果渲染器超出原始邊界範圍,則會複製邊緣顏色對超出範圍的地區進行著色 REPEAT的作用是在橫向和縱向上以平鋪的形式重複渲染位元影像 MIRROR的作用是在橫向和縱向上以鏡像的方式重複渲染位元影像 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用來指定顏色數組的相對位置;參數tile表示平鋪方式。通常,參數positions設為null,表示顏色數組以斜坡線的形式均勻分布。 下面這段代碼是直接從git上面的項目拷貝下來的 複製代碼package com.example.shimmer; import android.content.Context;import android.graphics.Canvas;import android.graphics.LinearGradient;import android.graphics.Matrix;import android.graphics.Paint;import android.graphics.Shader;import android.util.AttributeSet;import android.widget.TextView; public class MyTextView extends TextView { private LinearGradient mLinearGradient; private Matrix mGradientMatrix; private Paint mPaint; private int mViewWidth = 0; private int mTranslate = 0; private boolean mAnimating = true; public MyTextView(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(); if (mViewWidth > 0) { mPaint = getPaint(); mLinearGradient = new LinearGradient(-mViewWidth, 0, 0, 0, new int[] { 0x33ffffff, 0xffffffff, 0x33ffffff }, new float[] { 0, 0.5f, 1 }, Shader.TileMode.CLAMP); mPaint.setShader(mLinearGradient); mGradientMatrix = new Matrix(); } } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (mAnimating && mGradientMatrix != null) { mTranslate += mViewWidth / 10; if (mTranslate > 2 * mViewWidth) { mTranslate = -mViewWidth; } mGradientMatrix.setTranslate(mTranslate, 0); mLinearGradient.setLocalMatrix(mGradientMatrix); postInvalidateDelayed(50); } } }複製代碼 這段代碼主要是分兩步:一個是在onSizeChanged()即大小發生改變的時候,另外一個是onDraw()主要是用來做動畫的效果的, 首先我們先來onSizeChanged()裡面的代碼,在這段代碼中主要是定義了LinearGradient: mLinearGradient = new LinearGradient(-mViewWidth, 0, 0, 0, new int[] { 0x33ffffff, 0xffffffff, 0x33ffffff },new float[] { 0, 0.5f, 1 }, Shader.TileMode.CLAMP); 這段代碼可以這麼理解,它定義了一組漸層的數值是{ 0x33ffffff, 0xffffffff, 0x33ffffff },這組數值分別在相對應的0,0.5,1中顯示,0位置對應0x33ffffff顏色,0.5位置對應0xffffffff,1位置對應0x33ffffff,這個漸層的初始位置是在手機螢幕的外面x=(-mViewWidth,0)就是螢幕外面 最後來看一下這個onDraw()方法裡面是如何做動畫的 mTranslate += mViewWidth / 10;很簡單表示每一次運動的遞增值 if (mTranslate > 2 * mViewWidth) { mTranslate = -mViewWidth; }