在项目中,我们经常会碰到需要在TextView前面添加图片标签的需求,如果是文本一行就能显示的话,我们一般会使用TextView的setCompoundDrawables方法:
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), (drawable.getMinimumHeight()));
v.setCompoundDrawables(drawable, null, null, null);
textView.setCompoundDrawablePadding(6);
效果图:
但是,如果是TextView内容有多行,效果呢?
居然不是我们想要的样子?
class VipTagSpan(context: Context, drawable: Int, charSequence: CharSequence) : ImageSpan(context, drawable, DynamicDrawableSpan.ALIGN_BOTTOM) {
private val spannableString: SpannableString = SpannableString("[ $charSequence").apply {
setSpan(this@VipTagSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
override fun draw(
canvas: Canvas,
text: CharSequence,
start: Int,
end: Int,
x: Float,
top: Int,
y: Int,
bottom: Int,
paint: Paint
) {
canvas.save()
val transY = ((bottom - top) - drawable.bounds.bottom) / 2 + top + 2
canvas.translate(x, transY.toFloat())
drawable.draw(canvas)
canvas.restore()
}
fun getSpan(): SpannableString {
return spannableString
}
}
使用:
textView.text = VipTagSpan(
textView.context,
R.mipmap.image_paidcontent_article,
textView.text).getSpan()