LinearGradient实现文字一闪一闪

效果预览


实现方法

新建LinearGradientTextView,继承TextView,重写onSizeChanged和onDraw。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class LinearGradientTextView extends TextView {
private int mViewWidth;
private Paint mPaint;
private LinearGradient mLinearGradient;
private Matrix mMatrix;
private int mTranslate;
public LinearGradientTextView(Context context) {
super(context);
}
public LinearGradientTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public LinearGradientTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@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, Color.GRAY, Color.RED, Color.GREEN}, null, Shader.TileMode.MIRROR);
mPaint.setShader(mLinearGradient);
mMatrix = new Matrix();
}
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mMatrix != null) {
mTranslate += mViewWidth / 5;
if (mTranslate > 2 * mViewWidth) {
mTranslate = -mViewWidth;
}
mMatrix.setTranslate(mTranslate, 0);
mLinearGradient.setLocalMatrix(mMatrix);
postInvalidateDelayed(100);
}
}
}

LinearGradient有两个构造函数:
public LinearGradient(float x0, float y0, float x1, float y1, int[] colors, float[] positions,Shader.TileMode tile)
参数:
float x0: 渐变起始点x坐标
float y0:渐变起始点y坐标
float x1:渐变结束点x坐标
float y1:渐变结束点y坐标
int[] colors:颜色 的int 数组
float[] positions: 相对位置的颜色数组,可为null, 若为null,可为null,颜色沿渐变线均匀分布
Shader.TileMode tile: 渲染器平铺模式

xml调用

1
2
3
4
5
6
7
<com.wuxiaolong.apksample.LinearGradientTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="测试文字一闪一闪"
android:textSize="30sp" />

Shimmer-android

Shimmer-android,github上,TextView一闪一闪动画效果



联系作者

我的微信公众号:吴小龙同学,欢迎关注交流,公号回复关键字「1024」有惊喜哦。