Skip to content

Instantly share code, notes, and snippets.

@lukaskubanek
Created June 14, 2015 08:19
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • 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
}
@richimf
Copy link

richimf commented Jun 10, 2020

Xcode throws an error in let pathPtr = UnsafeMutablePointer<NSBezierPath>.alloc(1)

Type 'UnsafeMutablePointer' has no member 'alloc'

Do you know why this happen?

@lukaskubanek
Copy link
Author

lukaskubanek commented Jun 12, 2020

@richimf This is an old Swift code, most of the API has changed since it’s been posted here 5 years ago. The mentioned part, for example, now reads as follows:

UnsafeMutablePointer<NSBezierPath>.allocate(capacity: 1)

@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