20

In this SO question, someone asked for calculating an angle from three points. I need to do the opposite thing.

I want to draw a clock, and I have tiny tick images. An art dude made 60 of them, each with an individual and accurate shadow. So there are 60 distinct images at 10x10 points in size, already correctly rotated in the center of that square.

So every 6 degrees one tick image has to be placed. I would just need to calculate the x/y coordinate based on a center point, an radius and an angle.

So I have:

  • an center point
  • an radius
  • an angle

Is there an easy way to calculate the x/y coordinate with this? Maybe cocoa-touch already has a useful function or method for this?

Community
  • 1
  • 1
dontWatchMyProfile
  • 45,440
  • 50
  • 177
  • 260

3 Answers3

27

let a be the angle, (x,y) the center point and r the radius, then your point will be at

(x + r*cos(a), y + r*sin(a))
gio
  • 4,950
  • 3
  • 32
  • 46
unbeli
  • 29,501
  • 5
  • 55
  • 57
20

In mathematics, to calculate the Cartesian coordinates from the polar coordinates:

x = r * cos(A) + x0;
y = r * sin(A) + y0;

where (x0, y0) is the centre of your circle, r is the radius and A is the angle.

But that assumes the mathematics coordinate convention i.e. x increases as you move rightwards, y increases as you move upwards. This is the default for views on Mac OS X Cocoa but I don't know if it is the same on the iPhone.

Also angles start at 3 o clock and go anti-clockwise i.e. 3 o clock is 0 degrees, 12 o clock is 90 degrees, 9 o clock is 180 degrees and 6 o clock is 270 degrees.

Also, the C sine and cosine functions work in radians.

JeremyP
  • 84,577
  • 15
  • 123
  • 161
  • I've just realised that unbeli's answer already applies the correction to make the angle start at the top and go clockwise in the natural way you would expect for a clock face. – JeremyP May 26 '10 at 13:03
  • +1. I couldn't make unbeli's solution work, but yours did (using JavaScript that is). Here's a snippet for drawing a line from the center of an HTML5 canvas at the specified angle. Note the hack to get around starting at 3 o clock: x0 = ctx.canvas.width / 2; y0 = ctx.canvas.height / 2; ctx.lineTo( (x0 + r * Math.cos(toRad(angle-90))), (y0 + r * Math.sin(toRad(angle-90))) ); – Gojira Jun 17 '14 at 12:56
1

Your image (center) should be placed at the point (X,Y), where (x,y) are the coordinates of center point, and r is radius

X = x + (r/2)*cos(angle);
Y = y + (r/2)*sin(angle); 
Vimard
  • 1,209
  • 8
  • 7