画一个三角形

时间:2012-11-19 21:11:10

标签: objective-c ios ipad uibezierpath cgpoint

我试图让用户绘制三角形。我得到起点和终点并使用公式找到等边三角形的第三个点来创建三角形,但它似乎没有任何想法我怎么能这样做?也许使用一个圆圈,但我不知道如何去做。这是我目前的代码。

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;

1 个答案:

答案 0 :(得分:9)

这应该可以计算等边三角形的第三个点:

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];
// ...