Align text around ImageSpan center vertical bug修复

下面这篇是关于图文混排居中显示问题的解决方案。由于公司的直播项目的弹幕用到了文章中的

http://stackoverflow.com/questions/25628258/align-text-around-imagespan-center-vertical

CenteredImageSpan 但是图文确仍然无法实现居中对齐。    

经过调试发现

int transY =( bottom - b.getBounds().bottom +  // align bottom to bottom
        (drawableHeight - fontDescent + fontAscent) / 2)/5;  // align center to center
transY 这个值初以 5 就能很好的实现图文居中对齐。

没有谷歌账户和其他账号也就发到这上面。希望能帮到其他人。

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 of the text line grows with the image but the baseline of the text does not shift upward. When the image is noticeably larger than the text size, the effect is rather unsightly.

Here is a sample, the outline shows bounds of the TextView

I am trying to have the surrounding text be centered vertically with respect to the image being displayed. Here is the same sample with blue text showing the desired location:

Here are the constraints that I'm bound by:

  • I cannot use compound drawables. The images must be able to be shown between words.
  • The text may be multiline depending on the content. I have no control over this.
  • My images are larger than the surrounding text and I cannot reduce their size. While the sample image above is larger than the actual images (to demonstrate the current behavior), the actual images are still large enough that this problem is noticeable.

I've tried using the android:gravity="center_vertical" attribute on the TextView, but this does not have any effect. I believe this just vertically centers the text lines, but within the text line the text is still drawn at the bottom.

My current train of thought is to create a custom span that shifts the baseline of the text based on the height of the line and the current text size. This span would encompass the entire text, and I would have to compute the intersection with the ImageSpans so I can avoid shifting the images as well. This sounds rather daunting and I'm hoping someone can suggest another approach.

Any and all help is appreciated!

share improve this question
 
1  
Did you figure out how to do this? –  WindsurferOak  Oct 26 '14 at 18:22
1  
I am looking to achieve the same stuff, however, the answer of ptilli make it looks like it is working, but it is not really doing what shoud be done, which is centering the text with the cursor. I'll let you know if I can figure out something –  jujux789  Feb 2 '15 at 18:29
1  
Answers below works only with image smaller height than text. Author and me needs opposite trick –  ElSajko Oct 8 '15 at 22:40
 
Possible duplicate of Aligning ImageSpan to the top of the TextView –  rds  Jun 29 '16 at 10:11
 
@rds I'm not trying to align the image span, so I don't think this is a duplicate. –  Karakuri  Jun 30 '16 at 14:38

6 Answers

active oldest votes
up vote 17 down vote accepted

It might be a bit late but I've found a way to do it, no matter the image size. You need to create a class extending ImageSpan and override the methods getSize() and getCachedDrawable() (we don't need to change the last one, but this method from DynamicDrawableSpan is private and cannot be accessed in another way from the child class). In getSize(...), you can then redefined the way DynamicDrawableSpan set the ascent/top/descent/bottom of the line and achieve what you want to do.

Here's my class example:

public class CenteredImageSpan extends ImageSpan {

    // Extra variables used to redefine the Font Metrics when an ImageSpan is added
    private int initialDescent = 0;
    private int extraSpace = 0;

    public CenteredImageSpan(final Drawable drawable) {
        this(drawable, entry, DynamicDrawableSpan.ALIGN_BOTTOM);
    }

    public CenteredImageSpan(final Drawable drawable, final int verticalAlignment) {
        super(drawable, verticalAlignment);
    }

    @Override
    public Rect getBounds() {
        return getDrawable().getBounds();
    }

    @Override
    public void draw(final Canvas canvas) {
        getDrawable().draw(canvas);
    }


    //
    // Following methods are overriden from DynamicDrawableSpan.
    //

    // Method used to redefined the Font Metrics when an ImageSpan is added
    @Override
    public int getSize(Paint paint, CharSequence text,
                       int start, int end,
                       Paint.FontMetricsInt fm) {
        Drawable d = getCachedDrawable();
        Rect rect = d.getBounds();

        if (fm != null) {
            // Centers the text with the ImageSpan
            if (rect.bottom - (fm.descent - fm.ascent) => 0) {
                // Stores the initial descent and computes the margin available
                initialDescent = fm.descent;
                extraSpace = rect.bottom - (fm.descent - fm.ascent);
            }

            fm.descent = extraSpace / 2 + initialDescent;
            fm.bottom = fm.descent;

            fm.ascent = -rect.bottom + fm.descent;
            fm.top = fm.ascent;
        }

        return rect.right;
    }

    // Redefined locally because it is a private member from DynamicDrawableSpan
    private Drawable getCachedDrawable() {
        WeakReference<Drawable> wr = mDrawableRef;
        Drawable d = null;

        if (wr != null)
            d = wr.get();

        if (d == null) {
            d = getDrawable();
            mDrawableRef = new WeakReference<>(d);
        }

        return d;
    }

    private WeakReference<Drawable> mDrawableRef;
}

Let me know if you have any trouble with that class!

share improve this answer
 
1  
You just have to replace the ImageSpan you were using with the CenteredImageSpan and it will center your image automatically with the text –  jujux789  Oct 8 '15 at 17:18
1  
There is a bug, entry variable doesn't exists anywhere, but your code try to use it. –  ElSajko  Oct 8 '15 at 19:32
2  
@ElSajko I just tried this solution and it appears to be working fine for an image larger than the text height. The posted code does have some errors: remove the "entry" variable in one of the constructors, and change "=>" to ">=" in getSize() –  Karakuri  Oct 9 '15 at 14:49
2  
For some reason fm.descent = 3 * extraSpace / 8 + initialDescent; works and fm.descent = extraSpace / 2 + initialDescent; aligns the text to the top. Following this tutorial btw to add image and text: guides.codepath.com/android/… –  user824294  Dec 30 '15 at 5:10 
1  
Please use paint.getFontMetricsInt() instead of fm.Because fm is a middle variable –  chefish  Dec 29 '16 at 7:26
up vote 31 down vote

My answer tweaks the first answer. Actually I have tried both two methods above, and I don't think they are really center vertical. It would make the drawable more center if it's placed in between ascent anddescent, rather than top and bottom. So as to the second answer, it aligns the center of the drawable to the baseline of the text, rather than the center of that text. Here's my solution:

public class CenteredImageSpan extends ImageSpan {
  private WeakReference<Drawable> mDrawableRef;

  public CenteredImageSpan(Context context, final int drawableRes) {
    super(context, drawableRes);
  }

  @Override
  public int getSize(Paint paint, CharSequence text,
                     int start, int end,
                     Paint.FontMetricsInt fm) {
    Drawable d = getCachedDrawable();
    Rect rect = d.getBounds();

    if (fm != null) {
      Paint.FontMetricsInt pfm = paint.getFontMetricsInt();
      // keep it the same as paint's fm
      fm.ascent = pfm.ascent;
      fm.descent = pfm.descent;
      fm.top = pfm.top;
      fm.bottom = pfm.bottom;
    }

    return rect.right;
  }

  @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 drawableHeight = b.getIntrinsicHeight();
    int fontAscent = paint.getFontMetricsInt().ascent;
    int fontDescent = paint.getFontMetricsInt().descent;
    int transY = bottom - b.getBounds().bottom +  // align bottom to bottom
        (drawableHeight - fontDescent + fontAscent) / 2;  // align center to center

    canvas.translate(x, transY);
    b.draw(canvas);
    canvas.restore();
  }

  // Redefined locally because it is a private member from DynamicDrawableSpan
  private Drawable getCachedDrawable() {
    WeakReference<Drawable> wr = mDrawableRef;
    Drawable d = null;

    if (wr != null)
      d = wr.get();

    if (d == null) {
      d = getDrawable();
      mDrawableRef = new WeakReference<>(d);
    }

    return d;
  }
}

I also rewrite getSize to keep the FontMetrics of drawable the same as other text, otherwise the parent view won't wrap the content correctly.

share improve this answer
 
 
This is the best solution which answering my qusetion too. This is my question...stackoverflow.com/questions/31249475/… –  user3057361  Jul 8 '15 at 23:42
 
Works perfectly. Make sure you provide context and resource name when you use the class. Example:ImageSpan imageSpan = new CenteredImageSpan(getApplicationContext(), R.drawable.ic_youricon) (unlike the previous example) –  logic  Nov 27 '15 at 12:08 
1  
did'nt work on 4" device 480x800 hdpi icons get cut at bottom text is shown correctly, but worked on xxhdpi devices –  chin87  Apr 26 '16 at 10:27
 
Replace draw with this draw: 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; // this is the key transY -= paint.getFontMetricsInt().descent / 2; canvas.translate(x, transY); b.draw(canvas); canvas.restore(); } –  chin87  Apr 28 '16 at 6:00 
2  
If the icon is larger than the text,the icon wil be cut –  chefish  Dec 28 '16 at 11:23
up vote 12 down vote
ImageSpan imageSpan = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM) {
                public void draw(Canvas canvas, CharSequence text, int start,
                        int end, float x, int top, int y, int bottom,
                        Paint paint) {
                    Drawable b = getDrawable();
                    canvas.save();

                    int transY = bottom - b.getBounds().bottom;
                    // this is the key 
                    transY -= paint.getFontMetricsInt().descent / 2;

                    canvas.translate(x, transY);
                    b.draw(canvas);
                    canvas.restore();
                }
            };
share improve this answer
 
 
works well and simple. Could explain the bottom top, x y parameter' meanings? I can't understand and no docs explanation. Thanks –  Victor Choy  Dec 1 '15 at 20:22
 
replace draw from @misaka-10032 with this draw and code is working on all resolutions –  chin87  Apr 28 '16 at 6:03
up vote 4 down vote

I got a working solution by creating a class that inherits from ImageSpan.

Then modified draw implementation from DynamicDrawableSpan. At least this implementation works when my image height is less than font height. Not sure how this works for bigger images like yours.

@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 bCenter = b.getIntrinsicHeight() / 2;
    int fontTop = paint.getFontMetricsInt().top;
    int fontBottom = paint.getFontMetricsInt().bottom;
    int transY = (bottom - b.getBounds().bottom) -
        (((fontBottom - fontTop) / 2) - bCenter);


    canvas.translate(x, transY);
    b.draw(canvas);
    canvas.restore();
}

Also had to reuse implementation from DynamicDrawableSpan as it was private.

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;

And this is how I use it as static method that inserts image in front of the text.

public static CharSequence formatTextWithIcon(Context context, String text,
    int iconResourceId) {
    SpannableStringBuilder sb = new SpannableStringBuilder("X");

    try {
        Drawable d = context.getResources().getDrawable(iconResourceId);
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); 
        CenteredImageSpan span = new CenteredImageSpan(d); 
        sb.setSpan(span, 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        sb.append(" " + text); 
    } catch (Exception e) {
        e.printStackTrace();
        sb.append(text); 
    }

    return sb;

Maybe not a good practice there considering localization, but works for me. To set images in the middle of the text, you'd naturally need to replace tokens in text with spans.

share improve this answer
 
1  
what happens when you use a larger image? –  Karakuri  Oct 14 '14 at 21:01
up vote 0 down vote

After reading the source code of TextView, I think we can use the baseLine of eache text line which is "y". And it will work even if you set lineSpaceExtra.

public class VerticalImageSpan extends ImageSpan {

    public VerticalImageSpan(Drawable drawable) {
        super(drawable);
    }

    /**
     * update the text line height
     */
    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end,
                       Paint.FontMetricsInt fontMetricsInt) {
        Drawable drawable = getDrawable();
        Rect rect = drawable.getBounds();
        if (fontMetricsInt != null) {
            Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
            int fontHeight = fmPaint.descent - fmPaint.ascent;
            int drHeight = rect.bottom - rect.top;
            int centerY = fmPaint.ascent + fontHeight / 2;

            fontMetricsInt.ascent = centerY - drHeight / 2;
            fontMetricsInt.top = fontMetricsInt.ascent;
            fontMetricsInt.bottom = centerY + drHeight / 2;
            fontMetricsInt.descent = fontMetricsInt.bottom;
        }
        return rect.right;
    }

    /**
     * see detail message in android.text.TextLine
     *
     * @param canvas the canvas, can be null if not rendering
     * @param text the text to be draw
     * @param start the text start position
     * @param end the text end position
     * @param x the edge of the replacement closest to the leading margin
     * @param top the top of the line
     * @param y the baseline
     * @param bottom the bottom of the line
     * @param paint the work paint
     */
    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end,
                     float x, int top, int y, int bottom, Paint paint) {

        Drawable drawable = getDrawable();
        canvas.save();
        Paint.FontMetricsInt fmPaint = paint.getFontMetricsInt();
        int fontHeight = fmPaint.descent - fmPaint.ascent;
        int centerY = y + fmPaint.descent - fontHeight / 2;
        int transY = centerY - (drawable.getBounds().bottom - drawable.getBounds().top) / 2;
        canvas.translate(x, transY);
        drawable.draw(canvas);
        canvas.restore();
    }

}
share improve this answer
 
up vote -1 down vote

My improved version: drawable font metrics zoomed relative to text font metrics. So that line spacing will be calculate correctly.

@Override
public int getSize(Paint paint, CharSequence text,
                   int start, int end,
                   Paint.FontMetricsInt fm) {
    Drawable d = getCachedDrawable();
    Rect rect = d.getBounds();
    float drawableHeight = Float.valueOf(rect.height());


    if (fm != null) {
        Paint.FontMetricsInt pfm = paint.getFontMetricsInt();
        float fontHeight = pfm.descent - pfm.ascent;
        float ratio = drawableHeight / fontHeight;

        fm.ascent = Float.valueOf(pfm.ascent * ratio).intValue();
        fm.descent = Float.valueOf(pfm.descent * ratio).intValue();
        fm.top = fm.ascent;
        fm.bottom = fm.descent;
    }

你可能感兴趣的:(BUG)