【问题标题】:Android - stroke inside pathAndroid - 路径内描边
【发布时间】:2013-05-23 23:33:01
【问题描述】:

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

谢谢,

卡尔

【问题讨论】:

  • 我不明白这个问题,你能更具体一点吗?你的意思是说“所有的笔画都在路径内,而不是一半的笔画在里面,一半在外面”?
  • 假设我用黑色的 10 像素宽的笔触绘制一个形状,然后用红色的 5 像素宽的笔触在该形状上绘制,那么红色路径将是宽度的一半黑色路径,它将在中间,因为一半的笔划将在形状边界内,一半将在外部。相反,我想要的是整个笔画都在形状边界内。在上面的示例中,这意味着红色笔划位于黑色笔划的一侧,即最靠近形状边界的一侧

标签: android


【解决方案1】:

它似乎无法控制笔画的位置(即内部、中心或外部)。欲了解更多信息,请参阅: Android Paint stroke width positioning

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

final RectF rectF = new RectF(halfStrokeWidth, halfStrokeWidth, width - halfStrokeWidth, height - halfStrokeWidth);
canvas.drawRoundRect(rectF, roundX, roundY, paint);

【讨论】:

  • 好答案。我在网上找到的大多数答案都提到您应该“补偿”而不是“补偿方式”。
【解决方案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);

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

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

【讨论】:

  • 疼痛笔画宽度加倍可以解决问题!
【解决方案3】:

使用Canvas#clipPath(Path, Op)。但请注意,在 Android 3.0 和 reintroduced in 4.3 中删除了对剪切到硬件加速画布中路径的支持。 3.0-4.2 显然有一个workaround,但我没有办法对其进行测试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-28
    相关资源
    最近更新 更多