Skip to content

Instantly share code, notes, and snippets.

@rajeefmk
Created April 29, 2017 15:53
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rajeefmk/221eea0a0fa168f3f7cc666a52692641 to your computer and use it in GitHub Desktop.
Save rajeefmk/221eea0a0fa168f3f7cc666a52692641 to your computer and use it in GitHub Desktop.
Image Span used to center align the image with surrounding text inside a textview.
package com.hashlearn.common.utils;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.style.DynamicDrawableSpan;
import java.lang.ref.WeakReference;
public class CenterImageSpan extends DynamicDrawableSpan {
private WeakReference<Drawable> mDrawableRef;
public CenterImageSpan(Drawable mDrawable) {
mDrawableRef = new WeakReference<>(mDrawable);
}
@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) {
fm.ascent = -rect.bottom;
fm.descent = 0;
fm.top = fm.ascent;
fm.bottom = 0;
}
return rect.right;
}
@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 / 2);
Paint.FontMetricsInt fm = paint.getFontMetricsInt();
transY -= fm.descent - (fm.ascent / 2);
canvas.translate(x, transY);
b.draw(canvas);
canvas.restore();
}
@Override
public Drawable getDrawable() {
return mDrawableRef.get();
}
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;
}
}
@spatwardhan7
Copy link

Hey Muhammed! I found this gist through the medium article you posted. Thanks a lot! How do I integrateCenterImageSpan with the image getter though?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment