Skip to content

Instantly share code, notes, and snippets.

@sxcore
Forked from ffried/UIImage+Rotation.swift
Last active March 21, 2018 19:00
Show Gist options
  • Save sxcore/3bcf02012433c7b47d0133b55348df02 to your computer and use it in GitHub Desktop.
Save sxcore/3bcf02012433c7b47d0133b55348df02 to your computer and use it in GitHub Desktop.
Swift 4.0 updated version, without "bangs" and with proper variable naming.
extension UIImage {
func rotate(degrees: CGFloat) -> UIImage? {
let degreesToRadians: (CGFloat) -> CGFloat = {
return $0 / 180.0 * .pi
}
let rotatedViewBox = UIView(frame: CGRect(origin: CGPoint(x:0, y:0), size: size))
let transformation = CGAffineTransform(rotationAngle: degreesToRadians(degrees))
rotatedViewBox.transform = transformation
let rotatedSize = rotatedViewBox.frame.size
UIGraphicsBeginImageContext(rotatedSize)
guard let temporaryBitmap = UIGraphicsGetCurrentContext(), let transformingImage = cgImage else {
return nil
}
temporaryBitmap.translateBy(x: rotatedSize.width / 2.0, y: rotatedSize.height / 2.0)
temporaryBitmap.rotate(by: degreesToRadians(degrees))
temporaryBitmap.scaleBy(x: 1.0, y: -1.0)
let temporaryRect = CGRect(x: -size.width / 2, y: -size.height / 2, width: size.width, height: size.height)
temporaryBitmap.draw(transformingImage, in: temporaryRect)
guard let rotatedImage = UIGraphicsGetImageFromCurrentImageContext() else {
return nil
}
UIGraphicsEndImageContext()
return rotatedImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment