我们在开发文字背景色时候,往往ui设计稿是背景色只是文字区域,但是系统自带的BackgroundColorSpan 无法达到这样效果,所以我们需要自定义背景色。
|
?贴上自定义BackgroundColorSpan代码:
public class BetterHighlightSpan extends ReplacementSpan {
private int backgroundColor;
//行间距
private int lineSpacingExtra = 0;
//上下两行文字背景的间距
private int topSpacingExtra = 10;
public BetterHighlightSpan(int backgroundColor) {
this(backgroundColor, 0);
}
public BetterHighlightSpan(int backgroundColor, int lineSpacingExtra) {
this(backgroundColor, lineSpacingExtra, 10);
}
public BetterHighlightSpan(int backgroundColor, int lineSpacingExtra, int topSpacingExtra) {
super();
this.backgroundColor = backgroundColor;
this.lineSpacingExtra = lineSpacingExtra;
this.topSpacingExtra = topSpacingExtra;
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
return Math.round(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) {
// save current color
int oldColor = paint.getColor();
//set background color
RectF rect = new RectF(x, top + topSpacingExtra, x + paint.measureText(text, start, end), bottom - lineSpacingExtra);
paint.setColor(backgroundColor);
canvas.drawRect(rect, paint);
// revert color and draw text
paint.setColor(oldColor);
canvas.drawText(text, start, end, x, y, paint);
}
}
?
|