代码
public class GradientTextView extends TextView {
public GradientTextView(Context context) {
super(context);
}
public GradientTextView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public GradientTextView(Context context, @Nullable 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);
TextPaint paint = getPaint();
LinearGradient mLinearGradient = new LinearGradient(0, 0, w, 0,
Color.RED, Color.GREEN, Shader.TileMode.CLAMP);
paint.setShader(mLinearGradient);
}
}
1、在onSizeChanged里面给TextPaint设置一个LinearGradient
2、在使用的时候注意TextView文字的颜色,如果文字颜色带有透明度就会使实际效果与想要的效果有偏差