如何在给定线的起点和终点处找到箭头尖端点

时间:2012-09-09 21:27:47

标签: objective-c ios cocoa-touch core-graphics

考虑你有一条起点(x1,y1)和终点(x2,y2)的行。

为了在线上绘制一个箭头帽(在物镜-c中),我需要在给定箭头角度(45度)的情况下找到箭头的点(x3,y3,x4,y4),并且箭头长度(h)。

所以给定x1,y1,x2,y2,h,alpha是什么x3,y3,x4,y4?

添加了解释问题的图片。

如果答案可以在objective-c(使用UIBezierpath和CGPoint)中,那将非常感激。

谢谢!arrow drawing

1 个答案:

答案 0 :(得分:8)

#import <math.h>
#import <UIKit/UIKit.h>
#import <CoreGraphics/CoreGraphics.h>

float phi = atan2(y2 - y1, x2 - x1); // substitute x1, x2, y1, y2 as needed
float tip1angle = phi - M_PI / 4; // -45°
float tip2angle = phi + M_PI / 4; // +45°

float x3 = x2 - h * cos(tip1angle); // substitute h here and for the following 3 places
float x4 = x2 - h * cos(tip2angle);
float y3 = y2 -  h * sin(tip1angle);
float y4 = y2 -  h * sin(tip2angle);

CGPoint arrowStartPoint = CGPointMake(x1, y1);
CGPoint arrowEndPoint = CGPointMake(x2, y2);
CGPoint arrowTip1EndPoint = CGPointMake(x3, y3);
CGPoint arrowTip2EndPoint = CGPointMake(x4, y4);

CGContextRef ctx = UIGraphicsGetCurrentContext(); // assuming an UIView subclass
[[UIColor redColor] set];
CGContextMoveToPoint(ctx, arrowStartPoint.x, arrowStartPoint.y);
CGContextAddLineToPoint(ctx, arrowEndPoint.x, arrowEndPoint.y);
CGContextAddLineToPoint(ctx, arrowTip1EndPoint.x, arrowTip1EndPoint.y);
CGContextMoveToPoint(ctx, arrowEndPoint.x, arrowEndPoint.y);
CGContextAddLineToPoint(ctx, arrowTip2EndPoint.x, arrowTip2EndPoint.y);

我希望这会有所帮助:)