Search code examples
androidandroid-layouttextviewspannablestringimagespan

Reduce ImageSpan height and width


I'm setting an Image Drawable as a SpannableString to a TextView but the image comes out larger than the text making it look weird. I need to reduce the size of the imagespan such that it's the same height as the text:

Here's what I've tried:

drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());

SpannableStringBuilder builder = new SpannableStringBuilder(holder.temptext.getText());
builder.setSpan(new ImageSpan(drawable), selectionCursor - ":)".length(), selectionCursor, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
holder.temptext.setText(builder);
holder.temptext.setSelection(selectionCursor);

holder.caption.setText(builder);

Solution

  • You need to measure your TextView's height and use it instead of intrinsic bounds:

    int lineHeight = holder.temptext.getLineHeight();
    
    drawable.setBounds(0, 0, lineHeight, lineHeight);