Skip to content

Instantly share code, notes, and snippets.

@polok
Created January 12, 2017 06:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save polok/b8bb5a1659fc611632b1a4df94d5d450 to your computer and use it in GitHub Desktop.
Save polok/b8bb5a1659fc611632b1a4df94d5d450 to your computer and use it in GitHub Desktop.
Small function to rotate the image clockwise or counterclockwise
func rotate(image: UIImage, clockwise: Bool) -> UIImage {
var rotatedImage: UIImage?
let rotateSize = CGSize(width: image.size.height, height: image.size.width)
UIGraphicsBeginImageContextWithOptions(rotateSize, false, 1.0)
guard let context = UIGraphicsGetCurrentContext() else {
return image
}
if clockwise {
CGContextRotateCTM(context, CGFloat(M_PI_2))
CGContextTranslateCTM(context, 0, -image.size.height)
} else {
CGContextRotateCTM(context, CGFloat(-M_PI_2))
CGContextTranslateCTM(context, -image.size.width, 0)
}
image.drawInRect(CGRectMake(0, 0, image.size.width, image.size.height))
rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return rotatedImage ?? image
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment