从一个点到另一个的弯曲箭头

时间:2019-03-07 07:31:58

标签: ios swift

我需要从一个点到另一个画一条弯曲的箭头。我确实从扩展名下面得到了一条直线箭头。

extension UIBezierPath {

static func arrow(from start: CGPoint, to end: CGPoint, tailWidth: CGFloat, headWidth: CGFloat, headLength: CGFloat) -> UIBezierPath {
    let length = hypot(end.x - start.x, end.y - start.y)
    let tailLength = length - headLength

    func p(_ x: CGFloat, _ y: CGFloat) -> CGPoint { return CGPoint(x: x, y: y) }
    let points: [CGPoint] = [
        p(0, tailWidth / 2),
        p(tailLength, tailWidth / 2),
        p(tailLength, headWidth / 2),
        p(length, 0),
        p(tailLength, -headWidth / 2),
        p(tailLength, -tailWidth / 2),
        p(0, -tailWidth / 2)
    ]

    let cosine = (end.x - start.x) / length
    let sine = (end.y - start.y) / length
    let transform = CGAffineTransform(a: cosine, b: sine, c: -sine, d: cosine, tx: start.x, ty: start.y)

    let path = CGMutablePath()
    path.addLines(between: points, transform: transform)


    path.closeSubpath()

    return self.init(cgPath: path)
}}

我目前从上述代码中得到什么。 What I have now

我需要什么。

What I need

2 个答案:

答案 0 :(得分:0)

使用 addArc 方法创建曲线线(而不是直线):-

path.addArc(tangent1End: start, tangent2End: end, radius: 30)

path.addArc(center: CGPoint(x: 100, y: 100), radius: 30, startAngle: 270, endAngle: 360, clockwise: true, transform: transform)

答案 1 :(得分:0)

我创建了一个弯曲的箭头并使用了如下所述的二次贝塞尔路径:Core Graphics, Part 4: A Path! A Path!

Quad Curve Animation

path.move(to: firstPoint)
path.addQuadCurve(to: endPoint, control: controlPoint)

然后我通过找到控制点和终点之间的角度来创建箭头:

controlPoint.angle(to: endPoint)

然后我通过添加和减去这个角度并添加到终点的距离来找到绘制箭头线的点:

func offset(from point: CGPoint, distance: CGFloat, degrees: CGFloat) -> CGPoint {
    let radians = degrees * .pi / 180
    let vertical = sin(radians) * distance
    let horizontal = cos(radians) * distance
    return point.applying(CGAffineTransform(translationX: horizontal, y: vertical))
}

最后我只是在这两个点上画线。