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

根據需求來選擇用哪一個方法。函數

相關文章
相關標籤/搜索