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

 

版权声明:本文为revolve原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/revolve/p/9287692.html