How to rotate image in Swift?
set ImageView image
ImageView.transform = ImageView.transform.rotated(by: CGFloat(M_PI_2))
Swift 5
ImageView.transform = ImageView.transform.rotated(by: .pi) // 180˚ImageView.transform = ImageView.transform.rotated(by: .pi / 2) // 90˚ImageView.transform = ImageView.transform.rotated(by: .pi * 1.5) // 270˚
In one line:
rotatedViewBox.transform = CGAffineTransform(rotationAngle: CGFloat.pi/2)
This is an extension of UIImage
that targets Swift 4.0 and can rotate just the image without the need for a UIImageView
. Tested successfully that the image was rotated, and not just had its exif data changed.
import UIKitextension UIImage { func rotate(radians: CGFloat) -> UIImage { let rotatedSize = CGRect(origin: .zero, size: size) .applying(CGAffineTransform(rotationAngle: CGFloat(radians))) .integral.size UIGraphicsBeginImageContext(rotatedSize) if let context = UIGraphicsGetCurrentContext() { let origin = CGPoint(x: rotatedSize.width / 2.0, y: rotatedSize.height / 2.0) context.translateBy(x: origin.x, y: origin.y) context.rotate(by: radians) draw(in: CGRect(x: -origin.y, y: -origin.x, width: size.width, height: size.height)) let rotatedImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return rotatedImage ?? self } return self }}
To perform a 180 degree rotation, you can call it like this:
let rotatedImage = image.rotate(radians: .pi)
If for whatever reason it fails to rotate, the original image will then be returned.