TextView文字颜色渐变

TextView文字颜色渐变

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import android.graphics.LinearGradient
import android.graphics.Shader
import android.widget.TextView

/**
* 左到右渐变
*/
fun TextView.setHorizontalGradientTextColor(startColor: Int, endColor: Int) {
val x1 = this.paint.measureText(this.text.toString())//测量文本 宽度
val shader = LinearGradient(0f, 0f, x1, 0f, startColor, endColor, Shader.TileMode.CLAMP)
this.paint.shader = shader
this.invalidate()
}

/**
* 上到下渐变
*/
fun TextView.setVerticalGradientTextColor(startColor: Int, endColor: Int) {
val y1 = this.paint.textSize//测量文本 高度
val shader = LinearGradient(0f, 0f, 0f, y1, startColor, endColor, Shader.TileMode.CLAMP)
this.paint.shader = shader
this.invalidate()
}

使用方式,调用扩展方法即可

textView.setHorizontalGradientTextColor(Color.RED, Color.GREEN)

作者

Dench

发布于

2023-09-11

更新于

2023-09-11

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×