Search code examples
swiftcore-graphicsuibezierpathcgaffinetransform

Applying a transformation to UIBezierPath makes drawing disappear


maybe this is a stupid question, but I'm trying to apply a transformation to a path as simple as this:

let path = UIBezierPath(rect: CGRect(x: 10, y: 10, width: 20, height: 20))
path.apply(CGAffineTransform(rotationAngle: 2.0))
"colorLiteral".setFill()
path.fill()

And seems like the fact of adding the "apply" line, completely erases the shape on the view, whereas if I don't include that line, the shape appears on its place correctly.

I'm quite new at Swift so I guess I'm missing an important step on this? Thanks all!


Solution

  • Try this and remember rotationAngle takes Radians.

    let bounds = CGRect(x: 10, y: 10, width: 20, height: 20)
    let path = UIBezierPath(rect: bounds)
    path.apply(CGAffineTransform(translationX: -bounds.midX, y: -bounds.midY))
    path.apply(CGAffineTransform(rotationAngle: CGFloat.pi / 4))
    path.apply(CGAffineTransform(translationX: bounds.midX, y: bounds.midY))