swiftuikitios10image-rendering

Rotate image with UIGraphicsImageRenderer?


UIGraphicsImageRenderer was newly introduced in iOS 10. I was wondering if there is any possibility to rotate an UIImage with it (any custom angle). I know there is the classic way with CGContextRotateCTM.


Solution

  • You can setup UIGraphicsImageRenderer to create an image and with that call the UIGraphicsGetCurrentContext() and rotate the context

    let renderer = UIGraphicsImageRenderer(size:sizeOfImage)
    let image = renderer.image(actions: { _ in
        let context = UIGraphicsGetCurrentContext()
    
        context?.translateBy(x: orgin.x, y: orgin.y)
        context?.rotate(by: angle)
        context?.draw(image.cgImage!, in: CGRect(origin: CGPoint(x: -orgin.x,y: -orgin.y), size: size))
    }
    return image