Reputation: 68
i have a situation where the user will tap on the screen and enters the degrees and a line should to be draw from the tapped point in the given degree.
i am using the following path code to draw the line but i am not able to draw the line in the correct degree.
CGMutablePathRef path = CGPathCreateMutable();
CGPathMoveToPoint(path,NULL,touchx,touchy);
CGPathAddLineToPoint(path, NULL,endX, endY);
lineLayer = [CAShapeLayer layer];
[lineLayer setPath:path];
[lineLayer setFillColor:[[UIColor lightTextColor] CGColor]];
[lineLayer setStrokeColor:[[UIColor blackColor] CGColor]];
[lineLayer setAnchorPoint:CGPointMake(0.0f, 0.0f)];
[lineLayer setPosition:CGPointMake(0.0f, 0.0f)];
[drawingview.layer addSublayer:lineLayer];
CGPathRelease(path);
Upvotes: 0
Views: 927
Reputation: 131503
You posted code that creates a path with a start point, and and end point, but did not post the most important bit: how you calculate the end point.
I assume that's the part you need help with.
You need to use basic trigonometry. Trig on iOS is based on radians, so you will need to convert degrees to radians:
CGFloat radians = M_PI * degrees / 180.0;
Then you need to calculate your end point based on your start point.
Remember the mnemonic of the Indian chief "SOH CAH TOA" (sine = opposite/hypotenuse, cosine = adjacent/hypotenuse, tangent = opposite/adjacent).
Drawing a diagram of a right triangle with the angle in question on the left and the right angle on the right:
The X measurement is the adjacent side.
So, if cosine = adjacent/hypotenuse, then adjacent = cos * hypotenuse.
The hypotenuse of the triangle is the radius of the circle. Replacing variables:
x = cos(angle) * radius
The y measurement is the opposite side.
If sine = opposite/hypotenuse, then opposite = sine * hypotenuse.
The hypotenuse of the triangle is the radius of the circle. Replacing variables:
y = sin(angle) * radius
So your code to calculate the end-point might look like this:
CGFloat radius = 50; //Picked out of thin air; decide on a radius value
CGFloat deltaX = radius * cosf(radians);
CGFloat deltaY = radius * sinf(radians);
endX = touchX+deltaX;
endy = touchY+deltaY;
Upvotes: 2