您可以使用 CornerPathEffect 类寻求帮助!以绘制圆角矩形为例。
使用 canvas.drawRoundRect() 方法绘制带半径的背景颜色并设置 Style.FILL 时,您可以获得圆形矩形。然后用Style.STROKE和paint的宽度设置,用同样的方法在它上面画一个圆形的矩形边框,就可以得到一个边框了。
代码:
mBackgroundRectF.set(0, 0, mWidth, mHeight);
canvas.drawRoundRect(mBackgroundRectF, mRadius, mRadius, mBackgroundPaint);
// edge ajustment because paint stroke style is center align
float edge = mBorderWidth / 2;
mBackgroundRectF.set(edge, edge, mWidth - edge, mHeight - edge);
canvas.drawRoundRect(mBackgroundRectF, mRadius, mRadius, mBorderPaint);
现在看起来,它不是我想要的,在背景和边框之间有一些偏移:
before
让我们试试 CornerPathEffect:
mBackgroundRectF.set(0, 0, mWidth, mHeight);
canvas.drawRoundRect(mBackgroundRectF, mRadius, mRadius, mBackgroundPaint);
// edge ajustment because paint stroke style is center align
float edge = mBorderWidth / 2;
mBackgroundRectF.set(edge, edge, mWidth - edge, mHeight - edge);
// use CornerPathEffect and then use drawRect() method
mBorderPaint.setPathEffect(new CornerPathEffect(mRadius / 2));
canvas.drawRect(mBackgroundRectF, mBorderPaint);
现在看起来是正确的:
after