Skip to content

Instantly share code, notes, and snippets.

@myell0w
Last active July 18, 2023 13:14
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save myell0w/39631f89f6312815a78d3617017c23f7 to your computer and use it in GitHub Desktop.
Save myell0w/39631f89f6312815a78d3617017c23f7 to your computer and use it in GitHub Desktop.
Some helpers to make working with CGPaths in Swift easier
/*
Copyright 2021 Matthias Tretter
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import Foundation
/// Convenience extensions on CGPath
public extension CGPath {
public enum Step {
case moveToPoint(point: CGPoint)
case addLineToPoint(point: CGPoint)
case addQuadCurveToPoint(point: CGPoint, control: CGPoint)
case addCurveToPoint(point: CGPoint, control1: CGPoint, control2: CGPoint)
case closeSubpath
init(_ element: CGPathElement) {
switch element.type {
case .moveToPoint:
self = .moveToPoint(point: element.points[0])
case .addLineToPoint:
self = .addLineToPoint(point: element.points[0])
case .addQuadCurveToPoint:
self = .addQuadCurveToPoint(point: element.points[1], control: element.points[0])
case .addCurveToPoint:
self = .addCurveToPoint(point: element.points[2], control1: element.points[0], control2: element.points[1])
case .closeSubpath:
self = .closeSubpath
}
}
}
// MARK: - Properties
public var steps: [Step] {
var steps: [Step] = []
self.enumerateSteps { steps.append($0) }
return steps
}
/// all subpaths, if the path consists of several unconnected paths
public var subpaths: [CGPath] {
var paths: [CGPath] = []
var currentPath: CGMutablePath?
self.enumerateSteps { step in
switch step {
case .moveToPoint(let point):
currentPath = CGMutablePath()
currentPath!.move(to: point)
case .addLineToPoint(let point):
currentPath!.addLine(to: point)
case .addQuadCurveToPoint(let point, let control):
currentPath!.addQuadCurve(to: point, control: control)
case .addCurveToPoint(let point, let control1, let control2):
currentPath!.addCurve(to: point, control1: control1, control2: control2)
case .closeSubpath:
currentPath!.closeSubpath()
paths.append(currentPath!)
}
}
return paths
}
// MARK: - CGPath Convenience
public func enumerateSteps(_ block: (Step) -> Void) {
self.applyWithBlock {
let step = Step($0.pointee)
block(step)
}
}
/// creates a copy of a path, that is "bigger" than the original path by `width` points
public func fillableCopy(outsettingBy width: CGFloat) -> CGPath {
// we first create a stroked copy that outsets the shape by 6pt
let stroked = self.copy(strokingWithWidth: width, lineCap: .butt, lineJoin: .miter, miterLimit: 100000.0)
// filling this shape would look like stroking the original shape
// because the shape consists of 2 subpaths, the inner and the outer
// we remove any subpaths but the outermost to get a shape that actually
// fills the whole original shape but is bigger
return stroked.removingInnerSubpaths()
}
}
// MARK: - CustomDebugStringConvertible
extension CGPath: CustomDebugStringConvertible {
public var debugDescription: String {
let steps = self.steps.map { $0.debugDescription }
let stepDescription = steps.joined(separator: "\n")
return "<CGPath>\n" + stepDescription
}
}
extension CGPath.Step: CustomDebugStringConvertible {
public var debugDescription: String {
func rounded(_ point: CGPoint) -> String {
return String(format: "(%.2f, %.2f)", point.x, point.y)
}
switch self {
case .moveToPoint(let point):
return " | moveTo(\(rounded(point)))"
case .addLineToPoint(let point):
return " | addLineTo(\(rounded(point)))"
case .addQuadCurveToPoint(let point, let control):
return " | addQuadCurveTo(\(rounded(point)), control: \(rounded(control)))"
case .addCurveToPoint(let point, let control1, let control2):
return " | addCurveTo(\(rounded(point)), control1: \(rounded(control1)), control2: \(rounded(control2)))"
case .closeSubpath:
return " | closeSubpath"
}
}
}
// MARK: - Private
private extension CGPath {
func removingInnerSubpaths() -> CGPath {
return self.subpaths.max { $0.boundingBox.width < $1.boundingBox.width }!
}
}
@davidbjames
Copy link

It never occurred to me that you could "grow" (or "shrink") a path this way! Brilliant!

Would you feel okay about throwing an MIT license on this gist so we can use the code with a clear conscience? :)

@myell0w
Copy link
Author

myell0w commented Mar 15, 2021

@davidbjames done ☺️

@davidbjames
Copy link

Thanks so much!

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