Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@li2
Last active March 20, 2018 06:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save li2/2bd15dac3edfa33ac476 to your computer and use it in GitHub Desktop.
Save li2/2bd15dac3edfa33ac476 to your computer and use it in GitHub Desktop.
使 ImageSpan 和 text 居中对齐 & 高度一致。ImageSpan 有一个构造器接收 drawable,所以可以根据 TextView 高度,设置 drawable.setBounds(0, 0, height, height),因此 CenteredImageSpan 也就没必要了。 #tags: android-view
// From http://stackoverflow.com/questions/25628258/align-text-around-imagespan-center-vertical
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment