简体   繁体   English

TextView中的ImageSpan对齐

[英]ImageSpan alignment in TextView

I have a TextView which makes use of the android:lineSpacingMultiplier attribute to increase the spacing between lines, which works fine except for when I add an ImageSpan to the text. 我有一个TextView ,它利用android:lineSpacingMultiplier属性来增加行之间的间距,除了将ImageSpan添加到文本中之外,该方法都可以正常工作。

This causes the image to be aligned to the bottom of the space between lines, not the baseline of the text (as is specified when I create it). 这将使图像与行之间的空间的底部对齐,而不是与文本的基线对齐(这是我创建时指定的)。

I tried using the android:lineSpacingExtra attribute, with some success, the image was still positioned lower than it should be, but not as much. 我尝试使用android:lineSpacingExtra属性,但取得了一些成功,图像的位置仍然低于应有的水平,但幅度不大。 Is there an alternate way of increasing the space between lines without messing up the vertical alignment of the ImageSpan ? 是否有其他方法可以增加行之间的ImageSpan不会弄乱ImageSpan的垂直对齐方式?

When you construct the ImageSpan, you can specify a vertical alignment, one of ImageSpan.ALIGN_BOTTOM or ImageSpan.ALIGN_BASELINE . 构造ImageSpan时,可以指定垂直对齐方式,即ImageSpan.ALIGN_BOTTOMImageSpan.ALIGN_BASELINE I believe ImageSpan uses ALIGN_BOTTOM by default, so try a constructor that allows you to specify ALIGN_BASELINE . 我相信ImageSpan默认使用ALIGN_BOTTOM ,因此请尝试使用允许您指定ALIGN_BASELINE的构造ALIGN_BASELINE

I've encountered the same problem, line spacing changed the baseline, so it takes down the images when you input text... you have to implement your custom image span, by changing its draw method: 我遇到了同样的问题,行距更改了基线,因此当您输入文本时,行距会减少图像...您必须通过更改其draw方法来实现自定义图像跨度:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM