public class CenterAlignImageSpan extends ImageSpan {
/**
* 图片和文字的左边距
*/
private int mMarginLeft = 0;
/**
* 图片和文字的右边距
*/
private int mMarginRight = 0;
public CenterAlignImageSpan(@NonNull Drawable d) {
super(d);
}
public CenterAlignImageSpan(@NonNull Drawable d, int verticalAlignment) {
super(d, verticalAlignment);
}
public CenterAlignImageSpan(@NonNull Drawable d, int verticalAlignment, int marginLeft, int marginRight) {
super(d, verticalAlignment);
mMarginLeft = marginLeft;
mMarginRight = marginRight;
}
@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();
x = mMarginLeft + x;
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();
}
@Override
public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
return mMarginLeft + super.getSize(paint, text, start, end, fm) + mMarginRight;
}
}
网友评论