Created
June 14, 2015 08:19
-
-
Save lukaskubanek/1f3585314903dfc66fc7 to your computer and use it in GitHub Desktop.
NSBezierPath+CGPath.swift
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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@heestand-xyz The link you have posted returns 404. Can you share the gist for Swift 5.3?