Swift中CGPathApply的等效或替代?

时间:2014-06-17 23:33:09

标签: swift cgpath

pre-release documentation中似乎没有Swift版本的CGPathApply。有没有等价物或替代品?我正在尝试获取CGPath的所有子路径,以便我可以从不同的起点重绘它。

4 个答案:

答案 0 :(得分:33)

Swift 3.0

在Swift 3.0中,您可以像这样使用CGPath.apply

let path: CGPath = ...
// or let path: CGMutablePath

path.apply(info: nil) { (_, elementPointer) in
    let element = elementPointer.pointee
    let command: String
    let pointCount: Int
    switch element.type {
    case .moveToPoint: command = "moveTo"; pointCount = 1
    case .addLineToPoint: command = "lineTo"; pointCount = 1
    case .addQuadCurveToPoint: command = "quadCurveTo"; pointCount = 2
    case .addCurveToPoint: command = "curveTo"; pointCount = 3
    case .closeSubpath: command = "close"; pointCount = 0
    }
    let points = Array(UnsafeBufferPointer(start: element.points, count: pointCount))
    Swift.print("\(command) \(points)")
}

Swift 2.2

添加@convention(c)后,您现在可以直接从Swift调用CGPathApply。这是一个做必要魔术的包装器:

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)
        }
        print(sizeofValue(body))
        let unsafeBody = unsafeBitCast(body, UnsafeMutablePointer<Void>.self)
        CGPathApply(self, unsafeBody, callback)
    }
}

(请注意,我的代码中未提及@convention(c),但在核心图形模块中CGPathApply的声明中使用了let path = UIBezierPath(roundedRect: CGRectMake(0, 0, 200, 100), cornerRadius: 15) path.CGPath.forEach { element in switch (element.type) { case CGPathElementType.MoveToPoint: print("move(\(element.points[0]))") case .AddLineToPoint: print("line(\(element.points[0]))") case .AddQuadCurveToPoint: print("quadCurve(\(element.points[0]), \(element.points[1]))") case .AddCurveToPoint: print("curve(\(element.points[0]), \(element.points[1]), \(element.points[2]))") case .CloseSubpath: print("close()") } }

使用示例:

{{1}}

答案 1 :(得分:5)

(提示:如果您必须在iOS 11之前支持iOS,请使用公认的答案。如果您需要iOS 11,则此答案要容易得多。)

iOS 11 起,苹果公司对此问题提供了正式的答案:CGPath.applyWithBlock(_:)

这使得不必要的所有肮脏技巧都源于CGPath.apply(info:function:)是一个C函数的问题,该函数不允许以通常的快捷方式将信息传输进出函数。

以下代码允许您执行以下操作:

let pathElements = path.pathElements()

要做到这一点,请复制并粘贴

import CoreGraphics

extension CGPath {
    func pathElements() -> [PathElement] {
        
        var result = [PathElement]()

        self.applyWithBlock { (elementPointer) in
            let element = elementPointer.pointee
            switch element.type {
            case .moveToPoint:
                let points = Array(UnsafeBufferPointer(start: element.points, count: 1))
                let el = PathElement.moveToPoint(points[0])
                result.append(el)
            case .addLineToPoint:
                let points = Array(UnsafeBufferPointer(start: element.points, count: 1))
                let el = PathElement.addLineToPoint(points[0])
                result.append(el)
            case .addQuadCurveToPoint:
                let points = Array(UnsafeBufferPointer(start: element.points, count: 2))
                let el = PathElement.addQuadCurveToPoint(points[0], points[1])
                result.append(el)
            case .addCurveToPoint:
                let points = Array(UnsafeBufferPointer(start: element.points, count: 3))
                let el = PathElement.addCurveToPoint(points[0], points[1], points[2])
                result.append(el)
            case .closeSubpath:
                result.append(.closeSubpath)
            @unknown default:
                fatalError()
            }
        }
        
        return result
    }

}

public enum PathElement {

    case moveToPoint(CGPoint)
    case addLineToPoint(CGPoint)
    case addQuadCurveToPoint(CGPoint, CGPoint)
    case addCurveToPoint(CGPoint, CGPoint, CGPoint)
    case closeSubpath

}

或以此代码为例来说明如何自己使用CGPath.applyWithBlock(_:)

为完整起见,这是Apple的官方文档:https://developer.apple.com/documentation/coregraphics/cgpath/2873218-applywithblock

iOS 13 起,苹果公司给出了一个更为优雅的官方答案:使用SwiftUI(即使您的UI不在SwiftUI中)

将您的cgPath转换为SwiftUI Path

let cgPath = CGPath(ellipseIn: rect, transform: nil)
let path =  Path(cgPath)
path.forEach { element in
    switch element {
    case .move(let to):
        break
    case .line(let to):
        break
    case .quadCurve(let to, let control):
        break
    case .curve(let to, let control1, let control2):
        break
    case .closeSubpath:
        break
    }
}

变量element的类型为Path.Element,它是一个纯Swift枚举,因此甚至没有技巧来从元素中获取值。

为完整起见,这是Apple的官方文档:https://developer.apple.com/documentation/swiftui/path/3059547-foreach

答案 2 :(得分:4)

以下是Ole Begemann的great post(感谢@Gouldsc!)的重点,适用于Swift 3,允许访问组成UIBezierPath实例的各个元素:

extension UIBezierPath {

    var elements: [PathElement] {
        var pathElements = [PathElement]()
        withUnsafeMutablePointer(to: &pathElements) { elementsPointer in
            cgPath.apply(info: elementsPointer) { (userInfo, nextElementPointer) in
                let nextElement = PathElement(element: nextElementPointer.pointee)
                let elementsPointer = userInfo!.assumingMemoryBound(to: [PathElement].self)
                elementsPointer.pointee.append(nextElement)
            }
        }
        return pathElements
    }

}

public enum PathElement {

    case moveToPoint(CGPoint)
    case addLineToPoint(CGPoint)
    case addQuadCurveToPoint(CGPoint, CGPoint)
    case addCurveToPoint(CGPoint, CGPoint, CGPoint)
    case closeSubpath

    init(element: CGPathElement) {
        switch element.type {
        case .moveToPoint: self = .moveToPoint(element.points[0])
        case .addLineToPoint: self = .addLineToPoint(element.points[0])
        case .addQuadCurveToPoint: self = .addQuadCurveToPoint(element.points[0], element.points[1])
        case .addCurveToPoint: self = .addCurveToPoint(element.points[0], element.points[1], element.points[2])
        case .closeSubpath: self = .closeSubpath
        }
    }

}

答案 3 :(得分:1)

Dmitry Rodionov制作了一个将Swift函数转换为CFunctionPointer的函数(参见https://github.com/rodionovd/SWRoute/wiki/Function-hooking-in-Swift)。

#define kObjectFieldOffset sizeof(uintptr_t)

struct swift_func_object {
    uintptr_t *original_type_ptr;
#if defined(__x86_64__)
    uintptr_t *unknown0;
#else
    uintptr_t *unknown0, *unknown1;
#endif
    uintptr_t function_address;
    uintptr_t *self;
};


uintptr_t _rd_get_func_impl(void *func)
{
    struct swift_func_object *obj = (struct swift_func_object *)*(uintptr_t *)(func + kObjectFieldOffset);
    
    //printf("-->Address of C-Func %lx unk=%lx ori=%lx<--\n", obj->function_address, obj->unknown0, obj->original_type_ptr);
    return obj->function_address;
}

我正在使用CGPathApply以及Swift回调函数成功使用它。 (代码http://parker-liddle.org/CGPathApply/CGPathApply.zip) 虽然德米特里说这是一个反向工程功能而不是受支持的功能。