Created
February 9, 2016 17:17
-
-
Save Bashta/9b530680e513f3495bb2 to your computer and use it in GitHub Desktop.
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
// | |
// UIImageExtensions.swift | |
// Dating | |
// | |
// Created by Erison on 1/28/16. | |
// Copyright © 2016 Yuriy Berdnikov. All rights reserved. | |
// | |
import UIKit | |
extension UIImage { | |
/** | |
Rotate the UIImage by x degrees and flips it. | |
- Parameter degrees: Degrees to rotate the image | |
- Parameter flip: Bool value that flips the image. False by default | |
*/ | |
func imageRotatedByDegrees(degrees: CGFloat, flip: Bool = false) -> UIImage { | |
// calculate the size of the rotated view's containing box for our drawing space | |
let rotatedViewBox = UIView(frame: CGRect(origin: CGPointZero, size: size)) | |
let transform = CGAffineTransformMakeRotation(degrees.fromDegreesToRadians()); | |
rotatedViewBox.transform = transform | |
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. | |
CGContextTranslateCTM(bitmap, rotatedSize.width / 2.0, rotatedSize.height / 2.0); | |
// Rotate the image context | |
CGContextRotateCTM(bitmap, degrees.fromDegreesToRadians()); | |
// Now, draw the rotated/scaled image into the context | |
var yFlip: CGFloat | |
if(flip){ | |
yFlip = CGFloat(-1.0) | |
} else { | |
yFlip = CGFloat(1.0) | |
} | |
CGContextScaleCTM(bitmap, yFlip, -1.0) | |
CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage) | |
CGContextDrawImage(bitmap, CGRectMake(-size.width / 2, -size.height / 2, size.width, size.height), CGImage) | |
let rotatedImage = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return rotatedImage | |
} | |
/** | |
Takes an image and return the .Up orientation variant of it. Ignores mirrored cases. | |
- Parameter image: Image to be fliped to .Up orientation | |
*/ | |
func imageToUpOrientation() -> UIImage { | |
switch self.imageOrientation { | |
case .Up: | |
return self | |
case .Down: | |
return self.imageRotatedByDegrees(180) | |
case .Left: | |
return self.imageRotatedByDegrees(-90) | |
case .Right: | |
return self.imageRotatedByDegrees(0) | |
default: | |
return self | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment