import java.lang.ref.WeakReference;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.drawable.Drawable;
import android.text.style.ReplacementSpan;
import android.util.Log;
public class AdaptiveImageSpan extends ReplacementSpan {
private final static String LOG_TAG = "AdaptiveImageSpan";
private Context mContext;
private int mResourceId;
private int mHeight;
private int mLeading;
private WeakReference<Drawable> mDrawableRef;
public AdaptiveImageSpan(Context context, int resourceId) {
mResourceId = resourceId;
mContext = context;
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, FontMetricsInt fm) {
FontMetricsInt tempTm = fm;
if (tempTm == null) {
tempTm = new FontMetricsInt();
paint.getFontMetricsInt(tempTm);
}
if (tempTm != null) {
Log.i(LOG_TAG, LOG_TAG + " --> getSize - fm.bottom:" + tempTm.bottom + " - fm.top: "
+ tempTm.top);
mLeading = (tempTm.bottom - tempTm.descent) - (tempTm.top - tempTm.ascent);
Log.i(LOG_TAG, LOG_TAG + " --> getSize - fm.ascent:" + tempTm.ascent + " - fm.descent: "
+ tempTm.descent + " - fm.leading: " + tempTm.leading + " - leading: " + mLeading);
mHeight = tempTm.descent - tempTm.ascent - mLeading;
// mHeight = tempTm.bottom - tempTm.top;
if(tempTm.top * tempTm.bottom == 0){
return 0;
}
}
Drawable d = getCachedDrawable();
Rect rect = d.getBounds();
Log.i(LOG_TAG, LOG_TAG + " --> getSize size:" + rect.right + " - height: " + mHeight);
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) {
Log.i(LOG_TAG, LOG_TAG + " --> draw - text:" + text + " - height: " + (bottom - top));
Drawable b = getCachedDrawable();
canvas.save();
int transY = bottom - b.getBounds().bottom;
transY -= mLeading;
canvas.translate(x, transY);
b.draw(canvas);
canvas.restore();
}
private Drawable getCachedDrawable() {
WeakReference<Drawable> wr = mDrawableRef;
Drawable d = null;
if (wr != null) d = wr.get();
if (d == null) {
d = getDrawable();
mDrawableRef = new WeakReference<Drawable>(d);
}
return d;
}
public Drawable getDrawable() {
Drawable drawable = null;
drawable = mContext.getResources().getDrawable(mResourceId);
int width = 0;
if (drawable.getIntrinsicHeight() > 0 && mHeight > 0) {
width =
(int) ((drawable.getIntrinsicWidth() / (drawable.getIntrinsicHeight() * 1.0f)) * mHeight);
}
Log.i(LOG_TAG, LOG_TAG + " --> getDrawable - mHeight:" + mHeight + " - width: " + width);
if (width > 0) {
drawable.setBounds(0, 0, width, mHeight);
} else {
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
}
return drawable;
}
}