我正在使用@Override
ReplacementSpan
方法创建一个矩形。如何向其添加RoundCorner
和padding
?
代码:
@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);
}
我正在使用MeasureText:
private float measureText(Paint paint, CharSequence text, int start, int end) {
return paint.measureText(text, start, end);
}
在提出一些建议后,我做了这些更改,我可以看到Rounded
上的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;
}
答案 0 :(得分:5)
Canvas的方法为drawRoundRect。您必须提供要绘制的RectF
,Paint
和drawRect
以及两个代表x和rx
和ry
的参数y圆角的半径。 E.g。
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);
}
答案 1 :(得分:0)
这对我有用:
public static int cnvToDip(Context context,
int pixels)
{
return ((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, pixels, context.getResources().getDisplayMetrics()));
}
public static float[] getRoundRectangleShape(Context context,
int radius)
{
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point point = new Point();
display.getSize(point);
return new float[]{point.x / cnvToDip(context, radius),
point.x / cnvToDip(context, radius),
point.x / cnvToDip(context, radius),
point.x / cnvToDip(context, radius),
point.x / cnvToDip(context, radius),
point.x / cnvToDip(context, radius),
point.x / cnvToDip(context, radius),
point.x / cnvToDip(context, radius)};
}
ShapeDrawable shapeDrawable = new ShapeDrawable(new RoundRectShape(getRoundRectangleShape(context, 20), null, null));
shapeDrawable.getPaint().setColor(Color.BLUE);
@Override
public void draw(Canvas canvas)
{
super.draw(canvas);
shapeDrawable.draw(canvas);