前言
最近开发过程中要实现文本颜色渐变的效果。什么,文本颜色也要渐变?虽然不乐意,但是也只能说好吧…
先来点最终效果图
常规操作
常见的渐变做法有两种,原理其实都是一样的。都是创建一个 LinearGradient 对象,并将其设置到 TextView 的画笔中。
先来简单介绍下 LinearGradient
LinearGradient
Shader 子类,用于实现线性渐变的效果。常用的构造方法如下
public LinearGradient(float x0,
float y0,
float x1,
float y1,
int color0,
int color1,
Shader.TileMode tile)
参数说明
- (x0, y0):渐变起始点坐标
- (x1, y1):渐变结束点坐标
- color0:渐变起始颜色
- color1:渐变终止颜色
- tile:填充模式
- CLAMP:边缘拉伸。使用边缘颜色对区域外的范围进行填充
- REPEAT:重复模式。在水平和垂直两个方向上重复填充
- MIRROR:镜像模式。在水平和垂直两个方向上以镜像的方式重复填充,相邻图像间有间隙
做法一
继承 TextView,重写 onLayout 方法后设置 Shader
public class GradientTextView extends TextView {
...
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (changed) {
getPaint().setShader(new LinearGradient(0, 0, getWidth(