SpannableString添加ImageSpan居中处理
程序员文章站
2022-05-25 21:29:14
...
Android图文混排可以通过SpannableString来实现,但是imageSpan只提供了两种对齐方式:ALIGN_BOTTOM,ALIGN_BASELINE两种方式,并没有居中对齐方式。
自定义ImageSpan
public class CenterImageSpan extends ImageSpan {
public CenterImageSpan(Drawable drawable) {
super(drawable);
}
public CenterImageSpan(Bitmap bitmap) {
super(bitmap);
}
@Override
public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom,
@NonNull Paint paint) {
Drawable b = getDrawable();
Paint.FontMetricsInt fm = paint.getFontMetricsInt();
int transY = (y + fm.descent + y + fm.ascent) / 2 - b.getBounds().bottom / 2;//计算y方向的位移
canvas.save();
canvas.translate(x, transY);//绘制图片位移一段距离
b.draw(canvas);
canvas.restore();
}
}
使用方式
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//创建SpannableString对象
val sp = SpannableString("Test String")
//拿到所加图片的drawable对象
val drawable =context.getDrawable(R.drawable.iv_to_add)
drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
//给SpannableString设置ImageSpan
val imageSpan = CenterImageSpan(drawable)
sp.setSpan(imageSpan, sp.length - 1, sp.length, ImageSpan.ALIGN_BASELINE)
textview.text=sp
}