Android——SpannableString实现带圆角标签效果

本节是对以往章节的一个复习练习,用到的知识前面已经提到过,不知道的同学请参考前几篇文章。
Android——SpannableString字体大小不一致垂直居中

今天要实现的效果图如下:
在这里插入图片描述
RadiusBackgroundSpan

public class RadiusBackgroundSpan extends ReplacementSpan {
    private int fontSize = -1;
    private boolean isSp = true;
    private int margin;
    private int padding;
    private int radius;
    private int textColor;
    private int bgColor;

    public RadiusBackgroundSpan(int fontSize, int margin, int radius, int textColor, int bgColor) {
        this.fontSize = fontSize;
        this.margin = margin;
        this.radius = radius;
        this.textColor = textColor;
        this.bgColor = bgColor;
    }

    @Override
    public int getSize(@NonNull Paint paint, CharSequence text, int start, int end, @Nullable Paint.FontMetricsInt fm) {
        Paint newPaint = getCustomTextPaint(paint);
        return (int) newPaint.measureText(text, start, end) + margin * 2;
    }

    @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);

        int textWidth = (int) newPaint.measureText(text, start, end);

        RectF rect = new RectF();
        rect.top = top + margin;
        rect.bottom = bottom - margin;
        rect.left = (int) (x + margin);
        rect.right = rect.left + textWidth + margin;
        paint.setColor(bgColor);
        canvas.drawRoundRect(rect, radius, radius, paint);

        newPaint.setColor(textColor);
        Paint.FontMetrics fontMetrics = newPaint.getFontMetrics();
        int offsetX = (int) ((rect.right - rect.left - textWidth) / 2) + margin;
        int offsetY = (int) ((y + fontMetrics.ascent + y + fontMetrics.descent) / 2 - (top + bottom) / 2);
        canvas.drawText(text, start, end, x + offsetX, y - offsetY, newPaint);

    }

    private TextPaint getCustomTextPaint(Paint srcPaint) {
        TextPaint textPaint = new TextPaint(srcPaint);
        if (fontSize != -1) {
            textPaint.setTextSize(isSp ? fontSize * textPaint.density : fontSize);
        }
        return textPaint;
    }
}

MainActivity.java

private void radiusTagSpan() {
        String format = "哪吒之魔童降世上映新推荐";

        SpannableString ss = new SpannableString(format);
        RadiusBackgroundSpan radiusBackgroundSpan = new RadiusBackgroundSpan(35, 10, 10, getResources().getColor(R
                .color.white), getResources().getColor(R.color.red));
        ss.setSpan(radiusBackgroundSpan, format.length() - 3, format.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tvImageSpan.setText(ss);
    }

你可能感兴趣的:(Android,SpannableString,圆角标签)