Fit ImageSpan to TextView line height

13,024

Solution 1

You need to set the image's bounds to the TextView's line height. Eg:

myIcon.setBounds(0, 0, t.getLineHeight(),t.getLineHeight());

This of course assumes you want a square image. If not square, then you'll need to manually determine what the width value should be based off the line height.

Solution 2

To achieve correct height of included into textview drawables you should set them appropriate bounds. But firstly, we have to calculate them correctly. Especially its height.

After some experiments I realized that FontMetricsInt field from Paint class can be useful.

Paint textPaint = new Paint();
//obviously, we have to set textSize into Paint object
textPaint.setTextSize(textSize);
FontMetricsInt fontMetrics = textPaint.getFontMetricsInt();
setBounds(
        0,
        fontMetrics.ascent,
        widthForDrawable,
        fontMetrics.bottom
);

So, the top of our image is aligned using ascent value of FontMetricsInt and the bottom - with bottom value.

Share:
13,024
filippo
Author by

filippo

Updated on June 12, 2022

Comments

  • filippo
    filippo almost 2 years

    I need to put some icons inside my textview, but they don't fit the line height (look at the arrows):

    screenshoot

    I tried this:

    spannable.setSpan(new ImageSpan(context, entry.getValue(), ImageSpan.ALIGN_BOTTOM), Matcher.start(), matcher.end(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    t.setText(spannable, BufferType.SPANNABLE);
    

    and this:

        Drawable myIcon = c.getResources().getDrawable(R.drawable.myicon);
        myIcon.setBounds(0, 0, myIcon.getIntrinsicWidth(), myIcon.getIntrinsicHeight());
        spannable.setSpan(new ImageSpan(myIcon, ImageSpan.ALIGN_BASELINE), matcher.start(), matcher.end(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
    t.setText(spannable, BufferType.SPANNABLE);
    

    and in both cases i had the same result.

    I keep the icon in /res/drawable folder, and its size is 75x75px. I tried to lower the image resolution but they look blurred