【问题标题】:ImageSpan alignment in TextViewTextView 中的 ImageSpan 对齐
【发布时间】:2014-01-28 13:14:47
【问题描述】:

我有一个TextView,它使用android:lineSpacingMultiplier 属性来增加行间距,除了我在文本中添加ImageSpan 时,它工作正常。

这会导致图像与行间距的底部对齐,而不是文本的基线(正如我创建它时指定的那样)。

我尝试使用android:lineSpacingExtra 属性,并取得了一些成功,图像的位置仍然低于应有的位置,但不是那么多。有没有另一种方法可以增加行间距而不弄乱ImageSpan 的垂直对齐方式?

【问题讨论】:

    标签: android textview


    【解决方案1】:

    构造 ImageSpan 时,可以指定垂直对齐方式,ImageSpan.ALIGN_BOTTOMImageSpan.ALIGN_BASELINE 之一。我相信 ImageSpan 默认使用ALIGN_BOTTOM,因此请尝试使用允许您指定ALIGN_BASELINE 的构造函数。

    【讨论】:

    • 这是对我有用的解决方案。 ImageSpan span = new ImageSpan(getContext(), bitmap, DynamicDrawableSpan.ALIGN_BASELINE);
    【解决方案2】:

    我也遇到了同样的问题,行间距改变了基线,所以当你输入文字时它会删除图像...... 您必须通过更改其绘制方法来实现自定义图像跨度:

    public class CustomImageSpan extends ImageSpan{    
        public static final int ALIGN_TOP = 2;
        public static final int ALIGN_CUSTOM = 3;
        @Override
        public void draw(Canvas canvas, CharSequence text,
                         int start, int end, float x,
                         int top, int y, int bottom, Paint paint) {
            Drawable b = getCachedDrawable();
            canvas.save();
    
            int transY = bottom - b.getBounds().bottom;
            if (mVerticalAlignment == ALIGN_BASELINE) {
                transY -= paint.getFontMetricsInt().descent;
            } else if (mVerticalAlignment == ALIGN_TOP) {
                transY += paint.getFontMetricsInt().ascent;
            }
    
            canvas.translate(x, transY);
            b.draw(canvas);
            canvas.restore();
        }
            private Drawable getCachedDrawable() {
                WeakReference<Drawable> wr = mDrawableRef;
                Drawable d = null;
    
                if (wr != null)
                    d = wr.get();
    
                if (d == null) {
                    d = getDrawable();
                    mDrawableRef = new WeakReference<Drawable>(d);
                }
    
                return d;
            }
    
            private WeakReference<Drawable> mDrawableRef;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-12-21
      • 1970-01-01
      • 2014-10-27
      • 1970-01-01
      • 2018-05-21
      • 2011-10-02
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多