【问题标题】:Draw circular sector using Path使用路径绘制圆形扇区
【发布时间】:2016-08-03 11:36:18
【问题描述】:

我想画这样的东西:

因此,我想在每张照片上放置一个带有黑色区域的圆形扇形(切割弧)。我如何使用例如来实现这一点

canvas.draw(Path path, Paint paint);

我在下面尝试过,但没有达到我想要的效果:

Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.addCircle(getWidth() / 2, getHeight() / 2, getHeight() / 2, Path.Direction.CW);
path.addRect(0, getHeight() - 70, getWidth(), getHeight(), Path.Direction.CW);

【问题讨论】:

标签: android view path android-canvas


【解决方案1】:

你几乎让它工作了。您只需要在绘制之前剪切画布并使用Path.FillType.INVERSE_EVEN_ODD 来绘制您的扇区:

// Limit the drawable region of the canvas (saving the state before)
canvas.save();
canvas.clipRect(new Rect(0, canvas.getHeight() - 70, canvas.getWidth(), canvas.getHeight()));

Path path = new Path();
path.setFillType(Path.FillType.INVERSE_EVEN_ODD);
path.addCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getHeight() / 2, Path.Direction.CW);
path.addRect(0, canvas.getHeight() - 70, canvas.getWidth(), canvas.getHeight(), Path.Direction.CW);
canvas.drawPath(path, paint);

// Restore the canvas to the saved state to remove clip
canvas.restore();

// Draw more things on the canvas...

或者,您可以使用Canvas.drawArc (documentation)

我假设您的问题是您需要为您的扇区分配一个固定高度,因此您需要根据该高度计算 startAnglesweepAngledrawArc 方法的参数)(假设一个正方形图片)。这是示例代码(API 级别 15 兼容):

int sectorHeigh = 70; // The height of your sector in pixels

// Compute the start angle based on your desired sector height
float startAngle = (float) Math.toDegrees(Math.asin((canvas.getHeight() / 2f - sectorHeigh) / (canvas.getHeight() / 2f)));
// Add the arc (calculating the sweepAngle based on startAngle)
canvas.drawArc(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), startAngle, 2 * (90 - startAngle), false, paint);

另一种使用弧线绘制扇区的方法是创建Path 对象,使用Path.addArc (documentation) 添加弧线,然后使用Canvas.drawPath (documentation) 绘制它。

【讨论】:

  • 这是一个很好的答案!谢谢:)
猜你喜欢
  • 2011-10-08
  • 1970-01-01
  • 2014-11-20
  • 2022-01-09
  • 2014-02-07
  • 2011-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多