Last active
September 26, 2023 23:11
-
-
Save juliensagot/9749c3a1df28c38fb9f9 to your computer and use it in GitHub Desktop.
Convert NSBezierPath to CGPath (Swift 5.1, Xcode 11.3 (11C29))
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension NSBezierPath { | |
/// A `CGPath` object representing the current `NSBezierPath`. | |
var cgPath: CGPath { | |
let path = CGMutablePath() | |
let points = UnsafeMutablePointer<NSPoint>.allocate(capacity: 3) | |
if elementCount > 0 { | |
var didClosePath = true | |
for index in 0..<elementCount { | |
let pathType = element(at: index, associatedPoints: points) | |
switch pathType { | |
case .moveTo: | |
path.move(to: points[0]) | |
case .lineTo: | |
path.addLine(to: points[0]) | |
didClosePath = false | |
case .curveTo: | |
path.addCurve(to: points[2], control1: points[0], control2: points[1]) | |
didClosePath = false | |
case .closePath: | |
path.closeSubpath() | |
didClosePath = true | |
@unknown default: | |
break | |
} | |
} | |
if !didClosePath { path.closeSubpath() } | |
} | |
points.deallocate() | |
return path | |
} | |
} |
If you are targeting macOS 14 then
cgPath
is already part of the NSBezierPath API - https://developer.apple.com/videos/play/wwdc2023/10054/?time=676
Nice catch! What a time to be alive 😃
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Even though I did not mean "finally" but I share your view. It's sad to see how appkit is still years behind uikit but on the other hand I'm happy that there is at least some work is going on improving appkit API.