获取 UIBezierPath 的起点

Get the start point of a UIBezierPath

我创建了一个 UIBezierPath,但我不知道如何访问它的起点。我试过这样做:

let startPoint = path.currentPoint

属性 currentPoint 给了我最后一点,而不是起点。我需要起点的原因是因为我想在路径的起点放置一个图像。

有什么想法吗?

您需要下拉到 CGPath 并使用 CGPathApply 遍历元素。你只想要第一个,但你必须全部看。

我假设您的路径格式正确,并以 "move." 开头 对于 UIBezierPath 应该始终如此(我不知道有什么方法可以做到这一点不是真的。)

您需要 rob mayoff 的 CGPath.forEach 提供一些帮助,这非常棘手,但有了它就非常简单了:

// rob mayoff's CGPath.foreach
extension CGPath {
    func forEach(@noescape body: @convention(block) (CGPathElement) -> Void) {
        typealias Body = @convention(block) (CGPathElement) -> Void
        func callback(info: UnsafeMutablePointer<Void>, element: UnsafePointer<CGPathElement>) {
            let body = unsafeBitCast(info, Body.self)
            body(element.memory)
        }
        let unsafeBody = unsafeBitCast(body, UnsafeMutablePointer<Void>.self)
        CGPathApply(self, unsafeBody, callback)
    }
}

// Finds the first point in a path
extension UIBezierPath {
    func firstPoint() -> CGPoint? {
        var firstPoint: CGPoint? = nil

        self.CGPath.forEach { element in
            // Just want the first one, but we have to look at everything
            guard firstPoint == nil else { return }
            assert(element.type == .MoveToPoint, "Expected the first point to be a move")
            firstPoint = element.points.memory
        }
        return firstPoint
    }
}

在Swift3中,基本相同:

// rob mayoff's CGPath.foreach
extension CGPath {
    func forEach( body: @convention(block) (CGPathElement) -> Void) {
        typealias Body = @convention(block) (CGPathElement) -> Void
        func callback(info: UnsafeMutableRawPointer?, element: UnsafePointer<CGPathElement>) {
            let body = unsafeBitCast(info, to: Body.self)
            body(element.pointee)
        }
        let unsafeBody = unsafeBitCast(body, to: UnsafeMutableRawPointer.self)
        self.apply(info: unsafeBody, function: callback)
    }
}

// Finds the first point in a path
extension UIBezierPath {
    func firstPoint() -> CGPoint? {
        var firstPoint: CGPoint? = nil

        self.cgPath.forEach { element in
            // Just want the first one, but we have to look at everything
            guard firstPoint == nil else { return }
            assert(element.type == .moveToPoint, "Expected the first point to be a move")
            firstPoint = element.points.pointee
        }
        return firstPoint
    }
}

最简单的方法是

-子类化 UIBezierPath

-创建自定义 属性 作为起始点

-覆盖 moveToPoint 方法并在那里设置 startPoint 的值

class MyBezierPath: UIBezierPath {
    var startPoint :CGPoint?

    override func moveToPoint(point: CGPoint) {
        super.moveToPoint(point)
        startPoint=point;
    }
}

    var myBezier = MyBezierPath()
    myBezier.moveToPoint(CGPoint(x: 0, y: 0))
    myBezier.addLineToPoint(CGPoint(x: 100, y: 0))
    myBezier.addLineToPoint(CGPoint(x: 50, y: 100))