【Android UI】自定義TextView實現動態的文字閃動效果
阿新 • • 發佈:2019-02-13
這段時間一直在看自定義View感覺很有意思,今天剛剛看到了一個實現動態的文字閃動效果的自定義TextView,其原理是利用LinearGradient和Matrix來實現的,執行效果如下:
要想實現這一個效果,可以充分利用Android中Paint物件的Shader渲染器。通過設定一個不斷變化的LinearGradient,並使用帶有該屬性的Paint物件來繪製要顯示的文字。首先,在onSizeChanged()方法中進行一些物件的初始化工作,並根據View的寬頻設定一個LinearGradient漸變渲染器,程式碼如下所示:
@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(
0,
0 ,
mViewWidth,
0,
new int[]{
Color.BLUE, 0xffffffff,
Color.BLUE},
null,
Shader.TileMode.CLAMP);
mPaint.setShader(mLinearGradient);
mGradientMatrix = new Matrix();
}
}
}
其中最關鍵的就是使用getPaint()方法獲取當前繪製的TextView的Paint物件,並給這個Paint物件設定原生TextView沒有的LinearGradient屬性。最後,在onDraw()方法中,通過矩陣的方式不斷平移漸變效果,從而在繪製文字時,產生動態的閃動效果,程式碼如下:
@Override
protected 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);
}
}