13

我想绘制一个使用路径定义的形状,笔画宽度为 5,其中所有笔画都在路径内,而不是一半在里面,一半在外面。

谢谢,

卡尔

4

3 回答 3

7

它似乎无法控制笔画的位置(即内侧、中心或外侧)。有关更多信息,请参阅: Android 画笔宽度定位

我的解决方案是在绘制时偏移笔画宽度,例如,

final RectF rectF = new RectF(halfStrokeWidth, halfStrokeWidth, width - halfStrokeWidth, height - halfStrokeWidth);
canvas.drawRoundRect(rectF, roundX, roundY, paint);
于 2014-09-05T04:33:02.327 回答
2

您可以使用 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);

现在看起来,它不是我想要的,它在背景和边框之间有一些偏移:

让我们试试 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);

现在看起来是正确的:

于 2017-01-09T03:40:42.400 回答
2

使用Canvas#clipPath(Path, Op). 但请注意,在 Android 3.0 中删除了对剪切到硬件加速画布中路径的支持,并在 4.3 中重新引入。3.0-4.2显然有一个解决方法,但我没有办法测试它。

于 2017-01-09T03:59:25.030 回答