Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mayoff
Forked from juliensagot/NSBezierPath+cgPath.swift
Last active September 20, 2022 11:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayoff/d6d9738860ef2d0ac4055f0d12c21533 to your computer and use it in GitHub Desktop.
Save mayoff/d6d9738860ef2d0ac4055f0d12c21533 to your computer and use it in GitHub Desktop.
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
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