Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert NSBezierPath to CGPath (Swift 3.0 / Xcode 8b4 syntax)
import AppKit
public extension NSBezierPath {
public var CGPath: CGPath {
let path = CGMutablePath()
var points = [CGPoint](repeating: .zero, count: 3)
for i in 0 ..< self.elementCount {
let type = self.element(at: i, associatedPoints: &points)
switch type {
case .moveToBezierPathElement: path.moveTo(nil, x: points[0].x, y: points[0].y)
case .lineToBezierPathElement: path.addLineTo(nil, x: points[0].x, y: points[0].y)
case .curveToBezierPathElement: path.addCurve(nil, cp1x: points[0].x, cp1y: points[0].y, cp2x: points[1].x, cp2y: points[1].y, endingAtX: points[2].x, y: points[2].y)
case .closePathBezierPathElement: path.closeSubpath()
}
}
return path
}
}
@trudnai

This comment has been minimized.

Copy link

trudnai commented Nov 27, 2016

Thanks! In Swift 3 it seems few methods changed for the CGMutablePath, this is what works for me:

import AppKit

public extension NSBezierPath {
    
    public var CGPath: CGPath {
        let path = CGMutablePath()
        var points = [CGPoint](repeating: .zero, count: 3)
        for i in 0 ..< self.elementCount {
            let type = self.element(at: i, associatedPoints: &points)
            switch type {
            case .moveToBezierPathElement: path.move(to: CGPoint(x: points[0].x, y: points[0].y) )
            case .lineToBezierPathElement: path.addLine(to: CGPoint(x: points[0].x, y: points[0].y) )
            case .curveToBezierPathElement: path.addCurve(      to: CGPoint(x: points[2].x, y: points[2].y),
                                                          control1: CGPoint(x: points[0].x, y: points[0].y),
                                                          control2: CGPoint(x: points[1].x, y: points[1].y) )
            case .closePathBezierPathElement: path.closeSubpath()
            }
        }
        return path
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.