@RitcheeQinG
2020-09-07T02:12:06.000000Z
字数 1634
阅读 223
Android
内容较老,仅提供思路
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.v4.content.res.ResourcesCompat;
import android.text.style.ImageSpan;
import com.imlib.common.utils.IMUtils;
import net.appcloudbox.uniform.HSApplication;
public class CenterAlignSpanWithNum extends ImageSpan {
private int resId;
public CenterAlignSpanWithNum(@NonNull Drawable d, int resId) {
super(d);
this.resId = resId;
}
@Override
public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, @NonNull Paint paint) {
Drawable background = getDrawable();
Rect bounds = background.getBounds();
Paint.FontMetricsInt fm = paint.getFontMetricsInt();
int transY = (y + fm.descent + y + fm.ascent) / 2 - bounds.bottom / 2;//计算y方向的位移
canvas.save();
canvas.translate(x, transY);//绘制图片位移一段距离
background.draw(canvas);
canvas.restore();
String str = text.subSequence(start, end).toString();
paint.setTextSize(IMUtils.dip2px(13));
Rect textBounds = new Rect();
//获得字符串所占空间大小
paint.getTextBounds(str, 0, str.length(), textBounds);
paint.setColor(Color.parseColor("#121212"));
Typeface tf = null;
try {
tf = ResourcesCompat.getFont(HSApplication.getContext(), resId);
} catch (Resources.NotFoundException e) {
e.printStackTrace();
}
if (null == tf) {
tf = Typeface.create("sans-serif_medium", Typeface.NORMAL);
paint.setFakeBoldText(true); // semi-bold要比bold细一点
}
paint.setTypeface(tf);
float textX = x + bounds.width() / 2f - textBounds.width() / 2f + IMUtils.dip2px(2);
canvas.drawText(str, textX, (float) y, paint);
}
}