Android TextView中加入图片并居中显示

效果

image.png

解决方案:使用\color{red}{SpannableString}

 /**
     * 给字符串添加一个图片
     */
    fun strAddDrawble(context: Context, size:Int,str: String, drawable: Int): SpannableString {
        val ss = SpannableString(str)
        val drawable = context.resources.getDrawable(drawable)
        drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
        val imageSpan = CenterAlignImageSpan(drawable)
        ss.setSpan(imageSpan, 0, size, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return ss
    }

备注:根据自己的项目需求来设置开始位置,结束位置

CenterAlignImageSpan需要自定义,使图片现在在中间

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.style.ImageSpan;

import androidx.annotation.NonNull;

public class CenterAlignImageSpan extends ImageSpan {

    public CenterAlignImageSpan(Drawable drawable) {
        super(drawable);

    }

    public CenterAlignImageSpan(Bitmap b) {
        super(b);
    }

    @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();
    }
}

推荐阅读更多精彩内容