-
-
Save sxcore/3bcf02012433c7b47d0133b55348df02 to your computer and use it in GitHub Desktop.
Swift 4.0 updated version, without "bangs" and with proper variable naming.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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