Drawing a triangle

JProg picture JProg · Nov 19, 2012 · Viewed 7.4k times · Source

Im trying to allow users to draw a triangle shape. I'm getting the start point and the end point and using the formula to find the third point of a equilateral triangle to create the triangle but it doesn't seem to be working any ideas how I can do this? Maybe using a circle but I dont know how to go about that. Here is my current code.

NSValue *point = [_path objectAtIndex:0];
CGPoint startPoint = point.CGPointValue;

point = [_path lastObject];
CGPoint endPoint = point.CGPointValue;

 CGPoint thirdPoint = CGPointMake(((startPoint.x+endPoint.x)/2), (((startPoint.x-endPoint.x)/2)*(tan(60))+1));
 UIBezierPath *triangle = [UIBezierPath bezierPath];
 [triangle moveToPoint:startPoint];
 [triangle addLineToPoint:endPoint];
 [triangle addLineToPoint:thirdPoint];
 [triangle addLineToPoint:startPoint];
 triangle.lineWidth=size;

Answer

Martin R picture Martin R · Nov 19, 2012

This should work to compute the third point of an equilateral triangle:

CGPoint startPoint = ..., endPoint = ...;

CGFloat angle = M_PI/3; // 60 degrees in radians
// v1 = vector from startPoint to endPoint:
CGPoint v1 = CGPointMake(endPoint.x - startPoint.x, endPoint.y - startPoint.y);
// v2 = v1 rotated by 60 degrees:
CGPoint v2 = CGPointMake(cosf(angle) * v1.x - sinf(angle) * v1.y,
                         sinf(angle) * v1.x + cosf(angle) * v1.y);
// thirdPoint = startPoint + v2:
CGPoint thirdPoint = CGPointMake(startPoint.x + v2.x, startPoint.y + v2.y);

UIBezierPath *triangle = [UIBezierPath bezierPath];
[triangle moveToPoint:startPoint];
[triangle addLineToPoint:endPoint];
[triangle addLineToPoint:thirdPoint];
[triangle closePath];
// ...