我在 Canvas 上画了一个用黑色填充的圆圈,并将 Canvas 的背景颜色设置为红色。
我只希望黑色圆圈显示为我的 View ,但我也得到了红色。
我试过使用 canvas.clipPath() 它确实有效。我在网上搜索了一下,发现我们需要禁用硬件加速才能让它工作。我试过了,但它仍然有效。
尝试为特定 View 禁用硬件加速:
view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
还有整个应用程序:
android:hardwareAccelerated="false"
Dint 在这两种情况下都有效。 关于如何使其发挥作用的任何想法?
代码:
我在这里剪辑
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
this.canvas = canvas;
path.reset();
left = 50;
top = 50;
right = getWidth()- 50;
bottom = getHeight()-50;
RectF rectf = new RectF(left, top, right, bottom);
path.arcTo(rectf, startAngle, sweepAngle);
path.lineTo(linex, liney);
canvas.clipPath(path);
canvas.drawPath(path, paint);
//canvas.restore();
}
最佳答案
这不是剪辑路径的用途。当您绘制一条路径然后对其进行剪辑时 - 这意味着您将从该点开始在 Canvas 上绘制的其余内容将被该路径遮盖。 在你的情况下,你在裁剪 Canvas 之前绘制了一个红色背景 - 所以它遍及整个 Canvas ,然后你裁剪它但只在路径内绘制,所以裁剪是无用的。
您可以在该代码中获得所需的内容:
// Do not set any background to the view before
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
this.canvas = canvas;
path.reset();
left = 50;
top = 50;
right = getWidth()- 50;
bottom = getHeight()-50;
RectF rectf = new RectF(left, top, right, bottom);
path.arcTo(rectf, startAngle, sweepAngle);
path.lineTo(linex, liney);
canvas.clipPath(path);
canvas.drawRect(0, 0, getWidth(), getHeight(), Red Paint in here);
canvas.drawPath(path, paint);
//canvas.restore();
}
这样你就可以在 pathClip 之后绘制背景
你不会看到任何红色,因为你在它之后绘制了整个路径,如果我猜对了 - 你希望能够用一种颜色绘制圆的一部分,而其余部分则用其他颜色绘制 - 你可以如果您将剪辑的路径是完整的圆并且您绘制的路径将是您想要绘制的部分,则实现它
关于android - canvas.clip Path()即使在禁用硬件加速后也无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22828208/