ios – 获取UIBezierPath的起点

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

let startPoint = path.currentPoint

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

有任何想法吗?

解决方法

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

我假设你的道路格式正确,并以“移动”开始.对于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
    }
}

在Swift 3中,它基本相同:

// rob mayoff's CGPath.foreach
extension CGPath {
    func forEach( body: @convention(block) (CGpathelement) -> Void) {
        typealias Body = @convention(block) (CGpathelement) -> Void
        func callback(info: UnsafeMutableRawPointer?,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
    }
}

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...