Android Path addArc in canvas between two points

2019-07-14 05:51发布

问题:

I'm trying to draw an arc in android. In IOS, it's really easy to do it with this method

[path addArcWithCenter: radius: startAngle: endAngle: clockwise:]

In android, I have 3 points (the center of my circle, and the two points I want to draw an arc between) :

Point center = new Point(..., ...);
Point p1 = new Point(..., ...);
Point p2 = new Point(..., ...);

int radius = (int) Math.sqrt(Math.pow(p1.x - center.x, 2) + Math.pow(p1.y - center.y, 2));

But how can I use the Path.addArc method to draw an arc between p1 and p2 ? I have tried as said in (How to draw Arc between two points on the Canvas?) :

RectF oval = new RectF();
oval.set(p2.x - radius, p2.y - radius, p2.x + radius, p2.y + radius);
path.addArc(oval, startAngle, endAngle - startAngle);
// startAngle : angle between horizontal axis and p1 point
// endAngle : angle between horizontal axis and p2 point

But actually it doesn't draw the expected arc. I don't understand what is the first parameter of the addArc method ! What the RectF is supposed to be ?

Thanks,

回答1:

path.addArc adds an arc to the end of your path. Android draws the arc clockwise, so when looking at a circle O if my arc needs to be as a quarter circle, say if it was a clock from 12 o'clock to 3 o'clock I need RectF to represent the square that inside it I can draw my arc. Two additional parameters are startAngle and sweepAngle. startAngle in my example is 270 (12 o'clock is 270, 3 o'clock is 0, 6 o'clock is 90 and 9 o'clock is 180). sweepAngle is how long is your arc, in my example it's 90. if I want to draw a half circle then it's 180.

If you wish to draw counter clockwise you need to set sweepAngle to minus degrees. For example an arc from 3 o'clock to 12 o'clock of 90 degrees, I'll need the startAngle to be 90 and the sweepAngle to be -90 .

A great article that taught me all this is in this link: https://www.cumulations.com/blogs/5/UnderstandingSweepangleindrawArcmethodofandroid



回答2:

The first parameter is the bounds of oval defining the shape and size of the arc - your code is absolutely correct here. May be the problem is that in iOS you have to use radians, but in Android you have to use degrees.