3
    let renderer = UIGraphicsImageRenderer(size: CGSize(width: 500, height: 500))
    let image = renderer.image { context in
        let size = renderer.format.bounds.size
        UIColor.red.setFill()
        context.cgContext.fillEllipse(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        let x = 300 //center
        let y = 100 //center
        let w = 200
        let h = 60
        let r = 5.41 //radians
        UIColor.white.setFill()
        context.cgContext.fill(CGRect(x: x - w / 2, y: y - h / 2, width: w, height: h))
    }

The result is like this:

How can I rotate my white rectangle with rotation center in the middle of the rectangle before it is drawn in context?

enter image description here

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358

1 Answers1

2

You can rotate your context with the following api: https://developer.apple.com/documentation/coregraphics/cgcontext/1456228-rotate

This is what it looks like for your example:

            // applied 5 rectangles to visualize the rotation origin.
            for i in 0...5 {
                let r: CGFloat = 0.1 * CGFloat(i) //radians
                context.cgContext.rotate(by: r)
                UIColor.white.setFill()
                context.cgContext.fill(CGRect(x: x - w / 2, y: y - h / 2, width: w, height: h))
            }

example image

Note that the rotation occurs around the context's origin. If you want a different center, you may need to apply a translation first (translateBy(x:y:) - see apple documentation for details).

de.
  • 7,068
  • 3
  • 40
  • 69