-
以下是自己的一点思考和理解
- 一个需要绘制文字的背景添加圆角
- 需要绘制文字垂直的位置和两边的位置 ReplacementSpan 的 draw 方法返回的就是文字的基线。
- 同时需要注意的是绘制文字的时候,设置画笔的大小
public class RoundBackgroundColorSpan extends ReplacementSpan {
private int fontSize;
private int margin;
private int radius;
private int textColor;
private int bgColor;
private int mSize;
public static final int STYLE_FILL = 0;//填充
public static final int STYLE_STROCK = 1;//扫边。扫边颜色默认和字体颜色一致
private int mStyle;
public RoundBackgroundColorSpan(int fontSize, int margin, int radius, int textColor, int bgColor) {
this(fontSize, margin, radius, textColor, bgColor, STYLE_FILL);
}
public RoundBackgroundColorSpan(int fontSize, int margin, int radius, int textColor, int bgColor, int style) {
this.fontSize = fontSize;
this.margin = margin;
this.radius = radius;
this.textColor = textColor;
this.bgColor = bgColor;
this.mStyle = style;
}
@Override
public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
Paint newPaint = getCustomTextPaint(paint);
mSize = (int) newPaint.measureText(text, start, end) + margin * 2;
return mSize;
}
@Override
public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int
bottom, @NonNull Paint paint) {
Paint newPaint = getCustomTextPaint(paint);
RectF rect = new RectF(x, y + paint.ascent(), x + mSize, y + paint.descent());
// 设置背景矩形,x为文字左边缘的x值,y为文字的baseline的y值。
// paint.ascent()获得baseline到文字上边缘的值,
// paint.descent()获得baseline到文字下边缘
if (mStyle == STYLE_STROCK) {
paint.setColor(textColor);
paint.setStyle(Paint.Style.STROKE);
} else {
paint.setColor(bgColor);
paint.setStyle(Paint.Style.FILL);
}
canvas.drawRoundRect(rect, radius, radius, paint);
// 绘制字
newPaint.setAntiAlias(true);
newPaint.setColor(textColor);
// 获取文字的宽度
int textWidth = (int) newPaint.measureText(text, start, end);
// 获取文字左边的偏移量
int offsetX = (int) ((rect.right - rect.left - textWidth) / 2);
canvas.drawText(text, start, end, x + offsetX, y, newPaint);
}
private TextPaint getCustomTextPaint(Paint srcPaint) {
TextPaint textPaint = new TextPaint(srcPaint);
textPaint.setTextSize(sp2px(fontSize));
return textPaint;
}
private int sp2px(int sp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
sp,
MovieApplication.getApp().getResources().getDisplayMetrics());
}
}
- 代码中调用的方式
int radiusColor2 = getResources().getColor(R.color.colorAccent);
int radiusColor22 = getResources().getColor(R.color.pink);
String content2 = getString(R.string.content1);
SpannableString spanString2 = new SpannableString(content2);
int start2 = content2.indexOf("录了本");
int end2 = start2 + "录了本".length();
spanString2.setSpan(new RadiusBackgroundSpan(11, 80, 10, radiusColor22, radiusColor2, STYLE_STROCK),
start2, end2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
tvDest11111111.append(spanString2); // setText 都可以
网友评论