Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert NSBezierPath to CGPath (Swift 5.1, Xcode 11.3 (11C29))
extension NSBezierPath {
/// A `CGPath` object representing the current `NSBezierPath`.
var cgPath: CGPath {
let path = CGMutablePath()
let points = UnsafeMutablePointer<NSPoint>.allocate(capacity: 3)
let elementCount = self.elementCount
if elementCount > 0 {
var didClosePath = true
for index in 0..<elementCount {
let pathType = self.element(at: index, associatedPoints: points)
switch pathType {
case .moveTo:
path.move(to: CGPoint(x: points[0].x, y: points[0].y))
case .lineTo:
path.addLine(to: CGPoint(x: points[0].x, y: points[0].y))
didClosePath = false
case .curveTo:
let control1 = CGPoint(x: points[1].x, y: points[1].y)
let control2 = CGPoint(x: points[2].x, y: points[2].y)
path.addCurve(to: CGPoint(x: points[0].x, y: points[0].y), control1: control1, control2: control2)
didClosePath = false
case .closePath:
path.closeSubpath()
didClosePath = true
}
}
if !didClosePath { path.closeSubpath() }
}
points.deallocate()
return path
}
}
@rasronin

This comment has been minimized.

Copy link

@rasronin rasronin commented Mar 11, 2015

Pure awesomeness. Thank you.

@kaishin

This comment has been minimized.

Copy link

@kaishin kaishin 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.