Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert NSBezierPath to CGPath (Swift 4, Xcode 9.2)
extension NSBezierPath {
var cgPath: CGPath {
get { return self.transformToCGPath() }
}
/// Transforms the NSBezierPath into a CGPath
///
/// :returns: The transformed NSBezierPath
private func transformToCGPath() -> CGPath {
// Create path
var path = CGMutablePath()
var points = UnsafeMutablePointer<NSPoint>.allocate(capacity: 3)
let numElements = self.elementCount
if numElements > 0 {
var didClosePath = true
for index in 0..<numElements {
let pathType = self.element(at: index, associatedPoints: points)
switch pathType {
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))
didClosePath = false
case .curveToBezierPathElement:
path.addCurve(to: CGPoint(x: points[0].x, y: points[0].y), control1: CGPoint(x: points[1].x, y: points[1].y), control2: CGPoint(x: points[2].x, y: points[2].y))
didClosePath = false
case .closePathBezierPathElement:
path.closeSubpath()
didClosePath = true
}
}
if !didClosePath { path.closeSubpath() }
}
points.deallocate(capacity: 3)
return path
}
}
@rasronin

This comment has been minimized.

Copy link

commented Mar 11, 2015

Pure awesomeness. Thank you.

@kaishin

This comment has been minimized.

Copy link

commented May 24, 2015

👍

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.