代碼
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設(shè)置一個(gè)LinearGradient
2、在使用的時(shí)候注意TextView文字的顏色董饰,如果文字顏色帶有透明度就會(huì)使實(shí)際效果與想要的效果有偏差