我有一个适用于 TextView 的 SpannableString
fun appendIconBeforeText(context : Context, text : String, iconName : String, baseColor : String? = "#2da346") : SpannableStringBuilder{
val span = SpannableStringBuilder(" $text")
val start: Int = span.toString().indexOf(text)
val end: Int = text.length
val imgResId = context.resources.getIdentifier(iconName, "mipmap", context.packageName)
val drawable = ContextCompat.getDrawable(context, imgResId)!!.mutate()
drawable!!.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(Color.parseColor(baseColor), BlendModeCompat.SRC_ATOP)
drawable!!.setBounds(0, 0, convertDpToPixel(22, context).toInt(), convertDpToPixel(22, context).toInt())
val image = ImageSpan(drawable!!, ImageSpan.ALIGN_CENTER)
span.setSpan(image, 0, 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
span.setSpan(ForegroundColorSpan(Color.parseColor(baseColor)), start, start + end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
return span
}
然后我想对TextView应用渐变,文本渐变显示成功但只有图像不能应用渐变:
tv.post {
val length = tv.paint.measureText(tv.text.toString())
val angle = Math.toDegrees(gradient.angel.toDouble())
val endX = cos(angle) * length
val endY = sin(angle) * length
val shader = LinearGradient(0f, 0f, endX.toFloat(), endY.toFloat(), gradient.colors.toIntArray(), gradient.locations.toFloatArray(), Shader.TileMode.CLAMP)
tv.paint.shader = shader
tv.invalidate()
}
有人可以帮我这里有什么问题吗?谢谢