Creating UIBezierPath and CGPath as easily as SwiftUI's Path

Daily Coding Tip 007

Path provides an easy way to construct a shape using SwiftUI. The closure that we use to construct it passes in an instance that we then add lines and quad curves to.

UIBezierPath can be used to create SKShapeNode, which is used by SpriteKit to create custom shapes. Actually, that initializer uses a CGPath, but this can be accessed using the cgPath property of a UIBezierPath.

The main reason to construct a CGPath by first constructing a UIBezierPath is that CGPath itself doesn’t have methods that allow you to add lines and curves.

extension UIBezierPath {
var path: Path {
return Path(self.cgPath)
}
func addQuadCurve(to point: CGPoint, control: CGPoint) {
self.addQuadCurve(to: point, controlPoint: control)
}
convenience init(_ callback: (inout UIBezierPath) -> ()) {
var path = UIBezierPath()
callback(&path)
self.init(cgPath: path.cgPath)
}
}

This extension allows UIBezierPath to be constructed the same way as we would construct a SwiftUI Path. I’ve also added the addQuadCurve method.

Path in SwiftUI calls the second parameter control, not controlPoint, so I’ve included an addQuadCurve method for consistency between the two.


Get more Daily Coding Tips in your inbox!