Search code examples
iosswiftuiimageviewuikituigraphicscontext

UIGraphicsGetCurrentContext saves rotation state


I'm trying to draw imageView with image in it.

let context = UIGraphicsGetCurrentContext()
context?.translateBy(x: imageView.center.x, y: imageView.center.y)
context?.rotate(by: imageData.rotationAngle)
context?.translateBy(x: -imageView.center.x, y: -imageView.center.y)
imageView.image?.draw(in: imageView.frame)

I have this within loop with multiple UIImageViews and the next imageView seems to be affected by the previous rotation.

How am I supposed to reset that context before drawing new imageView?


Solution

  • You will want to use:

    if let context = UIGraphicsGetCurrentContext() {
      CGContextSaveGState(context)
      context.translateBy(x: imageView.center.x, y: imageView.center.y)
      context.rotate(by: imageData.rotationAngle)
      context.translateBy(x: -imageView.center.x, y: -imageView.center.y)
      imageView.image?.draw(in: imageView.frame)
      CGContextRestoreGState(context)
    }