将箭头附加到 UIBezierPath

append arrowhead to UIBezierPath

我需要你的帮助:

我正在尝试使用宽度可变的 UIBezierPaths 创建一个图形,该图形由带有两个控制点的贝塞尔曲线组成。现在我想在这些路径的末尾(右侧)添加箭头。有没有办法做到这一点,即通过附加一个包含三角形的较小 lineWidth 的子路径? 这是我要添加箭头的一些路径的示例图片:

感谢您的帮助!

假设您画了这样一条弧线:

UIBezierPath *path = [UIBezierPath bezierPath];

[path moveToPoint:point1];
[path addQuadCurveToPoint:point3 controlPoint:point2];

CAShapeLayer *shape = [CAShapeLayer layer];
shape.path = path.CGPath;
shape.lineWidth = 10;
shape.strokeColor = [UIColor blueColor].CGColor;
shape.fillColor = [UIColor clearColor].CGColor;
shape.frame = self.view.bounds;
[self.view.layer addSublayer:shape];

可以用atan2计算控制点到终点的角度:

CGFloat angle = atan2f(point3.y - point2.y, point3.x - point2.x);

请注意,使用四贝塞尔曲线还是立方曲线并不重要,思路是一样的。计算最后一个控制点到终点的角度。

然后您可以像这样计算三角形的角来放置箭头:

CGFloat distance = 15.0;
path = [UIBezierPath bezierPath];
[path moveToPoint:point3];
[path addLineToPoint:[self calculatePointFromPoint:point3 angle:angle + M_PI_2 distance:distance]]; // to the right
[path addLineToPoint:[self calculatePointFromPoint:point3 angle:angle          distance:distance]]; // straight ahead
[path addLineToPoint:[self calculatePointFromPoint:point3 angle:angle - M_PI_2 distance:distance]]; // to the left
[path closePath];

shape = [CAShapeLayer layer];
shape.path = path.CGPath;
shape.lineWidth = 2;
shape.strokeColor = [UIColor blueColor].CGColor;
shape.fillColor = [UIColor blueColor].CGColor;
shape.frame = self.view.bounds;
[self.view.layer addSublayer:shape];

我们使用 sinfcosf 计算角点的地方如下:

- (CGPoint)calculatePointFromPoint:(CGPoint)point angle:(CGFloat)angle distance:(CGFloat)distance {
    return CGPointMake(point.x + cosf(angle) * distance, point.y + sinf(angle) * distance);
}

这会产生类似的东西:

很明显,调整distance参数就可以控制三角形的形状了。