如何在Android中添加圆角到画布画?
作者:互联网
我在ReplacementSpan的@Override方法中创建一个矩形.如何添加RoundCorner和填充?
码:
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
RectF rect = new RectF(x, top, x + measureText(paint, text, start, end), bottom);
paint.setColor(mBackgroundColor);
canvas.drawRect(rect, paint);
paint.setColor(mForegroundColor);
canvas.drawText(text, start, end, x, y, paint);
}
编辑-1
我正在使用MeasureText:
private float measureText(Paint paint,CharSequence text,int start,int end){
return paint.measureText(text,start,end);
}
编辑-2
经过一些建议后我做了这些修改,我可以在Rectangle上看到圆角
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
RectF rect = new RectF(x, top, x + measureText(paint, text, start, end), bottom);
paint.setColor(mBackgroundColor);
canvas.drawRoundRect(rect, 15,15,paint);
paint.setColor(mForegroundColor);
canvas.drawText(text, start, end, x, y, paint);
}
这是截图:
我从以下代码调用draw方法:
int currentIndex = 0;
for (int i = 0; i < words.length - 1; i++) {
s.setSpan(new CustomDrawble(Color.GRAY, Color.WHITE), currentIndex, currentIndex + words[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
currentIndex += words[i].length() + 1;
}
解决方法:
Canvas的方法是drawRoundRect.你必须提供要绘制的RectF,Paint,如drawRect和两个加法参数,rx和ry,它们代表圆角的x和y半径.例如.
canvas.drawRoundRect(rect, 5, 5, paint);
将绘制一个圆角为5像素的矩形
EDIT2:
免责声明:使用dip而不是像素
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
RectF rect = new RectF(x, top, x + measureText(paint, text, start, end) + 10, bottom);
paint.setColor(mBackgroundColor);
canvas.drawRoundRect(rect, 15,15,paint);
paint.setColor(mForegroundColor);
canvas.drawText(text, start, end, x + 5, y, paint);
}
标签:drawrect,android,canvas 来源: https://codeday.me/bug/20190829/1762500.html