Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular sector shaped clipping mask with Path.addArc?

I need to create a clipping mask with a shape of a circular sector.

I am able to draw one using the following:

paint.setColor(0x88FF0000);
paint.setStyle(Style.FILL);
canvas.drawArc(oval, 0, 30, true, paint);

I want to use it as a clipping path, so I've tried:

Path path = new Path();
path.addArc(oval, 0, 30);
canvas.clipPath(path, Op.REPLACE);

However addArc doesn't have the useCenter parameter so what I get is not a sector but a segment.

like image 949
hthms Avatar asked May 13 '12 10:05

hthms


2 Answers

Ok, it seems there is no proper way doing this using a clipping mask.

However there is an alternate way using PorterDuffXfermode. See Xfermodes in ApiDemos.

I simply draw a sector using drawArc over my image with the DST_OUT operator. This makes the part of the image covered by the sector invisible (not drawn).

paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(0xFFFFFFFF);
paint.setStyle(Style.FILL);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));

canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
drawable.draw(canvas);
canvas.drawArc(oval, 30, 90, true, paint);
like image 198
hthms Avatar answered Sep 20 '22 04:09

hthms


I needed to tweak the AChartEngine library for Android to turn the pie chart into a donut chart. I needed to replace the following:

canvas.drawArc(oval, startAngle, sweepAngle, useCenter, paint);

by using the Path class in order to be able to use clipping. The following code did the job for me:

Path path = new Path();
path.moveTo(oval.centerX(), oval.centerY());
path.addArc(oval, startAngle, sweepAngle);
path.lineTo(oval.centerX(), oval.centerY());
canvas.drawPath(path, paint);

I hope this saves some headaches to people not familiar with the Canvas API as myself.

like image 29
argenkiwi Avatar answered Sep 19 '22 04:09

argenkiwi