Skip to content

Instantly share code, notes, and snippets.

@lukaskubanek
Created June 14, 2015 08:19
Show Gist options
  • Save lukaskubanek/1f3585314903dfc66fc7 to your computer and use it in GitHub Desktop.
Save lukaskubanek/1f3585314903dfc66fc7 to your computer and use it in GitHub Desktop.
NSBezierPath+CGPath.swift
import AppKit
public extension NSBezierPath {
public convenience init(path: CGPath) {
self.init()
let pathPtr = UnsafeMutablePointer<NSBezierPath>.alloc(1)
pathPtr.initialize(self)
let infoPtr = UnsafeMutablePointer<Void>(pathPtr)
// I hope the CGPathApply call manages the deallocation of the pointers passed to the applier
// function, but I'm not sure.
CGPathApply(path, infoPtr) { (infoPtr, elementPtr) -> Void in
let path = UnsafeMutablePointer<NSBezierPath>(infoPtr).memory
let element = elementPtr.memory
let pointsPtr = element.points
switch element.type {
case .MoveToPoint:
path.moveToPoint(pointsPtr.memory)
case .AddLineToPoint:
path.lineToPoint(pointsPtr.memory)
case .AddQuadCurveToPoint:
let firstPoint = pointsPtr.memory
let secondPoint = pointsPtr.successor().memory
let currentPoint = path.currentPoint
let x = (currentPoint.x + 2 * firstPoint.x) / 3
let y = (currentPoint.y + 2 * firstPoint.y) / 3
let interpolatedPoint = CGPoint(x: x, y: y)
let endPoint = secondPoint
path.curveToPoint(endPoint, controlPoint1: interpolatedPoint, controlPoint2: interpolatedPoint)
case .AddCurveToPoint:
let firstPoint = pointsPtr.memory
let secondPoint = pointsPtr.successor().memory
let thirdPoint = pointsPtr.successor().successor().memory
path.curveToPoint(thirdPoint, controlPoint1: firstPoint, controlPoint2: secondPoint)
case .CloseSubpath:
path.closePath()
}
pointsPtr.destroy()
}
}
// TODO: Add conversion to CGPath
}
@heestand-xyz
Copy link

@richimf
Copy link

richimf commented Aug 28, 2020

Great, thanks all of you.

@imthath-m
Copy link

@heestand-xyz The link you have posted returns 404. Can you share the gist for Swift 5.3?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment