textView颜色渐变显示

public TextView invalidateTv(TextView tv, String s, int tv_size, String start_color, String end_color) {
    tv.setTextSize(tv_size);
    tv.setText(s);
    int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    tv.measure(spec, spec);
    int measuredWidthTicketNum = tv.getMeasuredWidth();
//核心代码
    LinearGradient mLinearGradient = new LinearGradient(0, 0, measuredWidthTicketNum, 0,
            Color.parseColor(start_color),
            Color.parseColor(end_color),
            Shader.TileMode.REPEAT);
    tv.getPaint().setShader(mLinearGradient);
    tv.invalidate();
    return tv;
}

必定要注意textView宽度的获取(以前一直没有效果,由于获取的宽度为零)数组

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: 渲染器平铺模式


public LinearGradient(float x0, float y0, float x1, float y1, int color0, int color1,Shader.TileMode tile)
float x0: 渐变起始点x坐标
float y0:渐变起始点y坐标
float x1:渐变结束点x坐标
float y1:渐变结束点y坐标
int color0: 起始渐变色
int color1: 结束渐变色
Shader.TileMode tile: 渲染器平铺模式

根据需求来选择用哪一个方法。函数

相关文章
相关标签/搜索