public class TagSpan extends ReplacementSpan {
private int mSize;
private int mColor;
private int mTextSizePx;
private int mRadiusPx;
private int mRightMarginPx;
public TagSpan(int color, int textSizePx, int radiusPx, int rightMarginPx) {
mColor = color;
mTextSizePx = textSizePx;
mRadiusPx = radiusPx;
mRightMarginPx = rightMarginPx;
}
@Override
public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
mSize = (int) paint.measureText(text, start, end) + mRightMarginPx;
return mSize;
}
@Override
public void draw(@NonNull Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
drawTagRect(canvas, x, y, paint);
drawTagText(canvas, text, start, end, y, paint);
}
private void drawTagRect(Canvas canvas, float x, int y, Paint paint) {
paint.setColor(mColor);
paint.setAntiAlias(true);
Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
final float strokeWidth = paint.getStrokeWidth();
RectF oval = new RectF(x + strokeWidth + 0.5f, y + fontMetrics.ascent, x + mSize + strokeWidth + 0.5f - mRightMarginPx, y + fontMetrics.descent);
paint.setStyle(Paint.Style.STROKE);
canvas.drawRoundRect(oval, mRadiusPx, mRadiusPx, paint);
}
private void drawTagText(Canvas canvas, CharSequence text, int start, int end, int y, Paint paint) {
paint.setTextSize(mTextSizePx);
paint.setColor(mColor);
paint.setAntiAlias(true);
paint.setTextAlign(Paint.Align.CENTER);
Paint.FontMetrics fontMetrics = paint.getFontMetrics();
final int textCenterX = (mSize - mRightMarginPx / 2) / 2;
int textBaselineY = (int) (y - fontMetrics.descent / 2);
final String tag = text.subSequence(start, end).toString();
canvas.drawText(tag, textCenterX, textBaselineY, paint);
}
}