美文网首页
图片中心和文字中心对齐的ImageSpan

图片中心和文字中心对齐的ImageSpan

作者: 小相柳 | 来源:发表于2021-07-29 18:43 被阅读0次
    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;
        }
    }
    

    相关文章

      网友评论

          本文标题:图片中心和文字中心对齐的ImageSpan

          本文链接:https://www.haomeiwen.com/subject/pldfvltx.html