Christoph Christoph - 10 days ago 6
Swift Question

Rotate image with 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
.

Answer

Going through the documentation and also due to the lack of replies on this question, I assume that it is not possible with the new UIGraphicsImageRenderer. Here is how I solved it at the end of the day:

func changeImageRotation(forImage image:UIImage, rotation alpha:CGFloat) -> UIImage{

    var newSize:CGSize{
        let a = image.size.width
        let b = image.size.height

        let width = abs(cos(alpha)) * a + abs(sin(alpha)) * b
        let height = abs(cos(alpha)) * b + abs(sin(alpha)) * a

        return CGSize(width: width, height: height)
    }

    let size = newSize
    let orgin = CGPoint(x: size.width/2, y: size.height/2)

    UIGraphicsBeginImageContext(size)
    let context = UIGraphicsGetCurrentContext()

    context?.translateBy(x: orgin.x, y: orgin.y)
    context?.rotate(by: alpha)
    context?.draw(image.cgImage!, in: CGRect(origin: CGPoint(x: -orgin.x,y: -orgin.y), size: size))

    let newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage!
}

New Sizecorresponds to the rectangular area that is required to draw the rotated image without changing its overall size. The image is than rotated and drawn in the center. For more information on that, refer to this post.

Comments