Created
November 22, 2018 20:26
-
-
Save douglascabral/377014099a1c7ecee9afd308be845657 to your computer and use it in GitHub Desktop.
Rotate UIImage
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
import UIKit | |
extension UIImage { | |
public func imageRotatedByDegrees(degrees: CGFloat, flip: Bool) -> UIImage { | |
let radiansToDegrees: (CGFloat) -> CGFloat = { | |
return $0 * (180.0 / CGFloat.pi) | |
} | |
let degreesToRadians: (CGFloat) -> CGFloat = { | |
return $0 / 180.0 * CGFloat.pi | |
} | |
// calculate the size of the rotated view's containing box for our drawing space | |
let rotatedViewBox = UIView(frame: CGRect(origin: .zero, size: size)) | |
let t = CGAffineTransform(rotationAngle: degreesToRadians(degrees)); | |
rotatedViewBox.transform = t | |
let rotatedSize = rotatedViewBox.frame.size | |
// Create the bitmap context | |
UIGraphicsBeginImageContext(rotatedSize) | |
let bitmap = UIGraphicsGetCurrentContext() | |
// Move the origin to the middle of the image so we will rotate and scale around the center. | |
bitmap?.translateBy(x: rotatedSize.width / 2.0, y: rotatedSize.height / 2.0) | |
// // Rotate the image context | |
bitmap?.rotate(by: degreesToRadians(degrees)) | |
// Now, draw the rotated/scaled image into the context | |
var yFlip: CGFloat | |
if(flip){ | |
yFlip = CGFloat(-1.0) | |
} else { | |
yFlip = CGFloat(1.0) | |
} | |
bitmap?.scaleBy(x: yFlip, y: -1.0) | |
let rect = CGRect(x: -size.width / 2, y: -size.height / 2, width: size.width, height: size.height) | |
bitmap?.draw(cgImage!, in: rect) | |
let newImage = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return newImage! | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment