Android SpannableString 自定义圆角背景

效果图:

 

自定义圆角背景

package com.app.mobivans;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.text.style.ReplacementSpan;

/**
 * @author: 潇潇
 * @create on:  2019/3/5
 * @describe:DOTO
 */

public class RoundBackgroundColorSpan  extends ReplacementSpan {
    private int bgColor;
    private int textColor;
    public RoundBackgroundColorSpan(int bgColor, int textColor) {
        super();
        this.bgColor = bgColor;
        this.textColor = textColor;
    }
    @Override
    public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
        //这个地方返回的与其余字体的间距
        return ((int)paint.measureText(text, start, end)+60);
    }

    @Override
    public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
        int color1 = paint.getColor();
        paint.setColor(this.bgColor);
        //rx  ry 控制背景圆角的大小
        canvas.drawRoundRect(new RectF(x, top+1, x + ((int) paint.measureText(text, start, end)+40), bottom-1), 20, 20, paint);
        paint.setColor(this.textColor);
        canvas.drawText(text, start, end, x+20, y, paint);
        paint.setColor(color1);
    }
}

在activity的应用

String content = "承接公路隧道工程,可承接的工作级别3级使用全断面开挖法,10人团队";
        SpannableString spannableString=new SpannableString("工作"+content);
        spannableString.setSpan(new RoundBackgroundColorSpan(Color.parseColor("#FF3A36"),Color.parseColor("#FFFFFF")), 0, 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        text.setText(spannableString);

 

如有不对之处,望各路大神指点,小女子在此谢过O(∩_∩)O

 

你可能感兴趣的:(Android,开发)