Centering a CGPath in Swift

Recently I was trying to work out how to center a CGPath in Swift, and Google was failing me. I found a pretty quick and easy way to do it so I thought I’d drop it here for others to find.

Here’s the code:

let path = ... // create your path
let bb = path.boundingBox
var transform = CGAffineTransform.init(translationX: -bb.midX, y: -bb.midY)
let result = path.copy(using: &transform)!

Hopefully that will save someone else some time!

Leave a Reply

Your email address will not be published. Required fields are marked *