问题描述
我正在用ReplacementSpan
@Override
方法创建一个矩形。
如何向其添加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);
}
编辑-1
我正在使用 MeasureText:
private float measureText(Paint paint, CharSequence text, int start, int end) { return paint.measureText(text, start, end); }
编辑-2
经过一些建议,我进行了这些更改,我可以在Rectangle
上看到Rounded
@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;
}
1楼
Canvas 有方法。
您必须提供要绘制的RectF
和Paint
,对于drawRect
和两个附加参数, rx
和ry
,它们表示圆角的 x 和 y 半径。
例如
canvas.drawRoundRect(rect, 5, 5, paint);
将绘制一个圆角为 5pixels 的矩形
编辑2:
免责声明:使用倾角代替像素
@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);
}
2楼
这对我有用:
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);