ImageSpan 不显示或者变小
程序员文章站
2022-03-03 13:50:54
...
设置ImageSpan后不显示或者图片变小的问题~~
SpannableString spanString = new SpannableString(content);
// Drawable drawable = context.getResources().getDrawable(id);
// drawable.setBounds(0, 0, 52, 32);// 设置 bounds显示图片
Bitmap drawable = BitmapFactory.decodeResource(context.getResources(),id);
// drawable.setDensity(160); 设置默认缩放比,否则会取手机的density
CenterImageSpan imageSpan = new CenterImageSpan(context,drawable, -1000); // 建议的构造方法
spanString.setSpan(imageSpan, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
图文混排居中对齐 CenterImageSpan
默认对齐方式: ImageSpan.ALIGN_BOTTOM 和 ImageSpan.ALIGN_BASELINE
public class CenterImageSpan extends ImageSpan {
public CenterImageSpan(Context context, Bitmap b, int verticalAlignment) {
super(context, b, verticalAlignment);
}
@Override
public void draw(Canvas canvas, CharSequence text,int start, int end, float x,int top, int y, int bottom, Paint paint) {
Drawable b = getDrawable();
canvas.save();
int transY = bottom - b.getBounds().bottom;
if (mVerticalAlignment == ALIGN_BOTTOM) {
}if (mVerticalAlignment == ALIGN_BASELINE) {
transY -= paint.getFontMetricsInt().descent;
}else {
Paint.FontMetricsInt fm = paint.getFontMetricsInt();
transY = (y + fm.descent + y + fm.ascent) / 2 - b.getBounds().bottom / 2;
}
canvas.translate(x, transY);
b.draw(canvas);
canvas.restore();
}
}
推荐阅读