Android中TextView 多行文字末尾添加图片居中

private TextView text;
    String text="这里是多行文字";
    SpannableString newText = new SpannableString(text+ " ");
    int len = newText.length();
    //加载本地资源图片
    Drawable d = ContextCompat.getDrawable(mContext, (R.drawable.abc_pic));
    //距离文字左边距10dp
    d.setBounds(10, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
    //自定义图片居中
    CenterAlignImageSpan span = new CenterAlignImageSpan(d);
    newText.setSpan(span, len - 1, len, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    text.setText(newText);
 
     /**
      *  自定义图片居中
      */
    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();
     //计算y方向的位移
            int transY = (y + fm.descent + y + fm.ascent) / 2 - b.getBounds().bottom / 2;
            canvas.save();
     //绘制图片位移一段距离
            canvas.translate(x, transY);
            b.draw(canvas); canvas.restore();
        }
    }

内容转自网络,版权归原作者所有,转载请以链接形式标明本文地址
本文地址:http://www.xiaoyuhost.com/tech/99.html