Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw line given a center point and angle in iOS?

This is so much an iOS question as it is my current inability to do coordinate geometry. Given a CGPoint to act as a point that the line will pass through and an angle in radians. How do I draw a line that extends across to the bounds of the screen (infinite line)?

I am using Quartz2d to do this and the API for creating a line is limited to two points as input. So how do I convert a point and angle to two points on the bounds of the iOS device?

like image 883
jab Avatar asked Mar 14 '13 21:03

jab


1 Answers

This begins with simple trigonometry. You need to calculate the x and y coordinate of the 2nd point. With an origin of 0,0 and treating a line that goes straight to the right as 0 degrees, and going counterclockwise (anti-clockwise for some of you), you do:

double angle = ... // angle in radians
double newX = cos(angle);
double newY = sin(angle);

This assumes a radius of 1. Multiply each times a desired radius. Pick a number that will be bigger than the screen such as 480 for an iPhone or 1024 for an iPad (assuming you want points and not pixels).

Then add the original point to get the final point.

Assuming you have CGPoint start, double angle, and a length, your final point is:

double endX = cos(angle) * length + start.x;
double endY = sin(angle) * length + start.y;
CGPoint end = CGPointMake(endX, endY);

It's OK if the end point is off the screen.

like image 83
rmaddy Avatar answered Nov 03 '22 00:11

rmaddy