Skip to content

Instantly share code, notes, and snippets.

@TedaLIEz
Created January 10, 2020 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TedaLIEz/97f03a2cb842621f022bd27ba1dfd020 to your computer and use it in GitHub Desktop.
Save TedaLIEz/97f03a2cb842621f022bd27ba1dfd020 to your computer and use it in GitHub Desktop.
center_vertical image span
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.text.style.ImageSpan;
import androidx.annotation.Px;
public class CenterVerticalImageSpan extends ImageSpan {
private static final int STANDARD_PAD_WIDTH = 0;
@Px
private final int mPad;
public CenterVerticalImageSpan(Context context, int resourceId) {
super(context, resourceId);
mPad = STANDARD_PAD_WIDTH;
}
public CenterVerticalImageSpan(Drawable drawable) {
super(drawable);
mPad = STANDARD_PAD_WIDTH;
}
public CenterVerticalImageSpan(Drawable drawable, @Px int padding) {
super(drawable);
mPad = padding;
}
@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.bottom - fmPaint.top;
int drHeight = rect.bottom - rect.top;
int top = drHeight / 2 - fontHeight / 4;
int bottom = drHeight / 2 + fontHeight / 4;
fontMetricsInt.ascent = -bottom;
fontMetricsInt.top = -bottom;
fontMetricsInt.bottom = top;
fontMetricsInt.descent = top;
}
return rect.right + mPad;
}
@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();
int transY;
Paint.FontMetricsInt fm = paint.getFontMetricsInt();
transY = y + (fm.descent + fm.ascent) / 2
- drawable.getBounds().bottom / 2;
canvas.translate(x + mPad, transY);
drawable.draw(canvas);
canvas.restore();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment