1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > android 背景图片居中显示文字 Android ImageSpan 给文字设置圆角背景 并且文字

android 背景图片居中显示文字 Android ImageSpan 给文字设置圆角背景 并且文字

时间:2022-10-03 17:14:04

相关推荐

android 背景图片居中显示文字 Android ImageSpan 给文字设置圆角背景 并且文字

public class RadiusBackgroundSpan extends ReplacementSpan {

private int mColor;

private int mTvColor;

private int mTvSize;

/**

* @param color 背景颜色

* @param tvColor 需要改变文字颜色吗

* @param tvSize 需要改变文字大小吗

*/

public RadiusBackgroundSpan(int color, int tvColor, int tvSize) {

mColor = color;

mTvColor = tvColor;

mTvSize = tvSize;

}

@Override

public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {

//mSize就是span的宽度,span有多宽,开发者可以在这里随便定义规则

//我的规则:这里text传入的是SpannableString,start,end对应setSpan方法相关参数

//可以根据传入起始截至位置获得截取文字的宽度,最后加上左右两个圆角的半径得到span宽度

return (int) (paint.measureText(text, start, end));

}

@Override

public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {

paint.setColor(mColor);//设置背景颜色

//paint.setAntiAlias(true);// 设置画笔的锯齿效果

int bgPainth = Math.round(paint.getFontMetrics().descent - paint.getFontMetrics().ascent);

int bgSize = getSize(paint, text.subSequence(start, end), start, end, paint.getFontMetricsInt());

RectF oval =new RectF(x, y + paint.ascent(), x + bgSize, y + paint.descent() /2);

//设置文字背景矩形,x为span其实左上角相对整个TextView的x值,y为span左上角相对整个View的y值。paint.ascent()获得文字上边缘,paint.descent()获得文字下边缘

canvas.drawRoundRect(oval, (y + paint.descent()) /2, (y + paint.descent()) /2, paint);//绘制圆角矩形,第二个参数是x半径,第三个参数是y半径

//我这里是全圆。 你可以自己去根据你需要的。去除以

paint.setColor(mTvColor);//你需要的画笔文字颜色

paint.setTextSize(mTvSize);

int tvPainth = Math.round(paint.getFontMetrics().descent - paint.getFontMetrics().ascent);

int tvSize = getSize(paint, text.subSequence(0, 2), 0, 2, paint.getFontMetricsInt());

canvas.drawText(text, start, end, (bgSize - tvSize) /2, y - (bgPainth - tvPainth) /2 + (bgPainth - y) /2, paint);//绘制文字

}

}

android 背景图片居中显示文字 Android ImageSpan 给文字设置圆角背景 并且文字居中 背景居中。...

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。