android text 渐变色
方式1,全部字体渐变
用法
textView.setGradientColor(arrayOf("#F8E321", "#42FFD2"))
/** * 统一文字渐变色设置 * @param colors 渐变色字符串数组 * @param positions 渐变色位置数组,可为空 * @param start 渐变起始点,可为空 * @param end 渐变结束点,可为空 * @param tile 渐变模式,默认为CLAMP */ private fun TextView.setGradientColor( colors: Array<String>, positions: FloatArray? = null, start: PointF? = null, end: PointF? = null, tile: Shader.TileMode = Shader.TileMode.CLAMP ) { post { setTextColor(Color.WHITE)//必须设置字体颜色白色,否则android11 等版本可能出现颜色比预期正确数值色重,太黑问题 val intColors = colors.map { Color.parseColor(it) }.toIntArray() val gradient = LinearGradient( start?.x ?: paddingStart.toFloat(), start?.y ?: 0F, end?.x ?: measuredWidth.toFloat() - paddingEnd, end?.y ?: 0F, intColors, positions, tile ) paint.shader = gradient invalidate() } } private fun TextView.setNoGradientColor( ) { post { paint.shader = null invalidate() } }
方式二:部分字体渐变
用法
val spans = listOf(
Triple(
0,
num.toString().length,
GradientSpan(
Color.parseColor("#F8E321"),
Color.parseColor("#42FFD2"),
18.dp.toFloat(),
-0.1f
)
)
)
textView.applyGradientToText(spans)
`
import android.graphics.Canvas
import android.graphics.LinearGradient
import android.graphics.Paint
import android.graphics.Shader
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ReplacementSpan
import android.widget.TextView
class GradientSpan(private val startColor: Int, private val endColor: Int,
private val textSize:Float,
private val textSkewX:Float=0f, 字体倾斜角度
private val offsetX:Float=0f,偏移量
) : ReplacementSpan() {
override fun getSize(
paint: Paint,
text: CharSequence,
start: Int,
end: Int,
fm: Paint.FontMetricsInt?
): Int {
return paint.measureText(text, start, end).toInt()
}
override fun draw(
canvas: Canvas,
text: CharSequence,
start: Int,
end: Int,
x: Float,
top: Int,
y: Int,
bottom: Int,
paint: Paint
) {
val width = paint.measureText(text, start, end)
val gradient = LinearGradient(x, 0f, x + width, 0f, startColor, endColor, Shader.TileMode.CLAMP)
paint.textSize=textSize
// 开启模拟加粗效果
paint.isFakeBoldText = true
paint.shader = gradient
// 设置文字倾斜度,正值表示向右倾斜,负值表示向左倾斜
paint.textSkewX = textSkewX // 设置为斜体,-0.25是一个常用的斜体倾斜值
canvas.drawText(text, start, end, x+(textSize*textSkewX).toInt()+offsetX, y.toFloat(), paint)
paint.shader = null
}
}
fun TextView.applyGradientToText(spans: List<Triple<Int, Int, GradientSpan>>) {
val text = text.toString()
val spannableString = SpannableString(text)
spans.forEach { (start, end, span) ->
spannableString.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
}
setText(spannableString)
}
`