15

I have two points of circle and center of this circle. I want to draw an arc between these points. Method drawArc is to simple and doesn't fit my purpose. Anybody help?

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
CarolusPl
  • 639
  • 4
  • 9
  • 18

2 Answers2

28

You can use Canvas.drawArc, but you must compute the arguments it needs:

Lets say that the center of the circle is (x0, y0) and that the arc contains your two points (x1, y1) and (x2, y2). Then the radius is: r=sqrt((x1-x0)(x1-x0) + (y1-y0)(y1-y0)). So:

int r = (int)Math.sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0));
int x = x0-r;
int y = y0-r;
int width = 2*r;
int height = 2*r;
int startAngle = (int) (180/Math.PI*atan2(y1-y0, x1-x0));
int endAngle = (int) (180/Math.PI*atan2(y2-y0, x2-x0));
canvas.drawArc(x, y, width, height, startAngle, endAngle);

Good luck!

Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
botismarius
  • 2,977
  • 2
  • 30
  • 29
  • FYI: This code would work a bit better if you used `float` instead of `int` variables. PI=3.14, Square Roots, etc. You could be creating a lot of zeros if you stick with `int` types. –  Dec 18 '12 at 22:30
  • 4
    in theory yes. however, drawArc() has int parameters. – botismarius Dec 19 '12 at 22:26
  • Note that r = Math.hypot(x1-x0, y1 - 0) – vdolez Nov 01 '16 at 08:19
  • Currently this `canvas.drawArc()` has 2 parameters more and is designed for API 21. Use overriden version if you need < 21. – CoolMind May 14 '20 at 07:49
2

Graphics.drawArc expects the following parameters:

  • x
  • y
  • width
  • height
  • startAngle
  • arcAngle

Given your arc start and end points it is possible to compute a bounding box where the arc will be drawn. This gives you enough information to provide parameters: x, y, width and height.

You haven't specified the desired angle so I guess you could choose one arbitrarily.

Adamski
  • 54,009
  • 15
  • 113
  • 152