Adam Styrc
Adam Styrc

Reputation: 1537

Draw circular sector using Path

I would like to draw something like this:

enter image description here

So on each photo I would like to put a circular sector (cut arc) with black area. How can I achieve that with using e.g.

canvas.draw(Path path, Paint paint);

I tried below but it didn t work out as I would like to:

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);

Upvotes: 2

Views: 1497

Answers (1)

antonio
antonio

Reputation: 18262

You almost had it working. You just need to clip the canvas before drawing and use Path.FillType.INVERSE_EVEN_ODD to draw your sector:

// 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...

Alternativelly, you can use Canvas.drawArc (documentation)

I assume from you question that you need to assign a fix height for your sector, so you will need to compute startAngle and sweepAngle (parameters of the drawArc method) based on that height (assuming a square image). Here is the sample code (API level 15 compatible):

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);

Another way to draw your sector using arcs is creating a Path object, add an arc using Path.addArc (documentation) and then use Canvas.drawPath (documentation) to draw it.

Upvotes: 1

Related Questions