将箭头附加到 UIBezierPath [英] append arrowhead to UIBezierPath
问题描述
我需要你的帮助:
我正在尝试使用具有可变宽度的 UIBezierPaths 创建一个图形,该图形由带有两个控制点的贝塞尔曲线组成.现在我想在这些路径的末端(右侧)添加箭头.有没有办法做到这一点,即通过附加一个包含三角形的较小 lineWidth 的子路径?这是我想添加箭头的一些路径的示例图片:
I am trying to create a graph using UIBezierPaths with variable widths and consisting of a bezier curve with two control points. Now I'd like to add arrow heads to the end (right hand side) of these paths. Is there a way to do this i.e. by appending a subpath with a smaller lineWidth which contains a triangle? here is a sample picture of some paths to which I'd like to add arrowheads:
感谢您的帮助!
推荐答案
假设你画了一个这样的弧线:
Let's assume you drew one of arcs like so:
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
来计算控制点到终点的角度:
You can use atan2
to calculate the angle from the control point to the final point:
CGFloat angle = atan2f(point3.y - point2.y, point3.x - point2.x);
请注意,使用四边形贝塞尔曲线还是三次方并不重要,想法是一样的.计算最后一个控制点到终点的角度.
Note, it doesn't really matter if you use quad bezier or cubic, the idea is the same. Calculate the angle from the last control point to the end point.
然后你可以通过计算三角形的角来放置一个箭头,如下所示:
You could then put an arrow head by calculating the corners of the triangle like so:
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];
我们使用 sinf
和 cosf
像这样计算角点:
Where we use sinf
and cosf
to calculate the corners like so:
- (CGPoint)calculatePointFromPoint:(CGPoint)point angle:(CGFloat)angle distance:(CGFloat)distance {
return CGPointMake(point.x + cosf(angle) * distance, point.y + sinf(angle) * distance);
}
结果如下:
显然,只需调整distance
参数即可控制三角形的形状.
Clearly, just adjust the distance
parameters to control the shape of the triangle.
这篇关于将箭头附加到 UIBezierPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!