4

是否有任何解决方法可以知道 a CGpath(使用坐标数组创建)在哪里关闭

我无法在标题中找到任何合适的方法CGPath

我希望跟踪用户跟踪的路径。如果它是一个闭环,那么我希望从上下文中提取该部分。诸如屏蔽或剪辑上下文之类的东西,但它应该是用户跟踪的剪辑。

谢谢!

4

2 回答 2

2

实际上,一条路径可以由多个子路径组成。当您移动路径的当前点而不连接两个点时,将创建一个新的子路径。对于要关闭的路径,它的所有子路径实际上必须是关闭的。

extension CGPath {

    /// Note that adding a line or curve to the start point of the current
    /// subpath does not close it. This can be visualized by stroking such a
    /// path with a line cap of `.butt`.
    public var isClosed: Bool {
        var completedSubpathsWereClosed = true
        var currentSubpathIsClosed = true

        self.applyWithBlock({ pointer in
            let element = pointer.pointee

            switch element.type {
            case .moveToPoint:
                if !currentSubpathIsClosed {
                    completedSubpathsWereClosed = false
                }

                currentSubpathIsClosed = true
            case .addLineToPoint, .addQuadCurveToPoint, .addCurveToPoint:
                currentSubpathIsClosed = false
            case .closeSubpath:
                currentSubpathIsClosed = true
            }
        })

        return completedSubpathsWereClosed && currentSubpathIsClosed
    }
}
于 2019-01-06T17:07:55.137 回答
1

以防你在过去的 4 1/2 年一直坚持这一点,这里是如何在 Swift 3 中做到这一点。我从这个答案中大量借鉴。我真的只是添加了这个功能。isClosed()

extension CGPath {

func isClosed() -> Bool {
    var isClosed = false
    forEach { element in
        if element.type == .closeSubpath { isClosed = true }
    }
    return isClosed
}

func forEach( body: @convention(block) (CGPathElement) -> Void) {
    typealias Body = @convention(block) (CGPathElement) -> Void
    let callback: @convention(c) (UnsafeMutableRawPointer, UnsafePointer<CGPathElement>) -> Void = { (info, element) in
        let body = unsafeBitCast(info, to: Body.self)
        body(element.pointee)
    }
    print(MemoryLayout.size(ofValue: body))
    let unsafeBody = unsafeBitCast(body, to: UnsafeMutableRawPointer.self)
    self.apply(info: unsafeBody, function: unsafeBitCast(callback, to: CGPathApplierFunction.self))
}
}

并假设pathCGPathor CGMutablePath,这是你如何使用它:

path.isClosed()
于 2017-07-16T04:06:19.740 回答