Align text around ImageSpan center vertical

前端 未结 9 1873
抹茶落季
抹茶落季 2020-11-28 23:59

I have an ImageSpan inside of a piece of text. What I\'ve noticed is that the surrounding text is always drawn at the bottom of the text line -- to be more precise, the size

9条回答
  •  广开言路
    2020-11-29 00:27

    My answer tweaks the misaka-10032 answer. work perfect!

    public static class CenteredImageSpan extends ImageSpan {
        private WeakReference mDrawableRef;
    
        CenteredImageSpan(Context context, final int drawableRes) {
            super(context, drawableRes);
        }
    
        public CenteredImageSpan(@NonNull Drawable d) {
            super(d);
        }
    
        @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 = getCachedDrawable();
            canvas.save();
            int transY = top + (bottom - top - b.getBounds().bottom)/2;
            canvas.translate(x, transY);
            b.draw(canvas);
            canvas.restore();
        }
    
        // Redefined locally because it is a private member from DynamicDrawableSpan
        private Drawable getCachedDrawable() {
            WeakReference wr = mDrawableRef;
            Drawable d = null;
    
            if (wr != null)
                d = wr.get();
    
            if (d == null) {
                d = getDrawable();
                mDrawableRef = new WeakReference<>(d);
            }
    
            return d;
        }
    }
    

提交回复
热议问题