Last active
January 30, 2016 03:53
-
-
Save yuvalt/1d077f4ad657a7edbdaa to your computer and use it in GitHub Desktop.
Extension of UIImage the helps cropping an image with an example of how to use the result of UIImagePickerController. Credit: original Objective-C code: http://blog.cmgresearch.com/2012/07/14/Cropping-the-results-from-UIImagePickerController.html
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
/* | |
Usage example: | |
// MARK - UIImagePickerControllerDelegate | |
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { | |
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage { | |
let cropRect = info[UIImagePickerControllerCropRect]?.CGRectValue | |
let croppedImage = pickedImage.crop(cropRect) | |
self.anImage.contentMode = .ScaleAspectFit | |
self.anImage.image = croppedImage | |
} | |
dismissViewControllerAnimated(true, completion: nil) | |
} | |
*/ | |
extension UIImage { | |
func crop(rect: CGRect?) -> UIImage { | |
guard let rect = rect else { | |
return self | |
} | |
// create a graphics context of the correct size | |
UIGraphicsBeginImageContext(rect.size) | |
let context = UIGraphicsGetCurrentContext() | |
var cropRect: CGRect? | |
// correct for image orientation | |
if imageOrientation == .Up { | |
CGContextTranslateCTM(context, 0, size.height) | |
CGContextScaleCTM(context, 1, -1) | |
cropRect = CGRectMake(rect.origin.x, | |
-rect.origin.y, | |
rect.size.width, | |
rect.size.height); | |
} | |
else if imageOrientation == .Right { | |
CGContextScaleCTM(context, 1.0, -1.0) | |
CGContextRotateCTM(context, CGFloat(-M_PI / 2.0)) | |
cropRect = CGRectMake(rect.origin.y, | |
rect.origin.x, | |
rect.size.height, | |
rect.size.width) | |
} | |
else if imageOrientation == .Down { | |
CGContextTranslateCTM(context, size.width, 0); | |
CGContextScaleCTM(context, -1, 1); | |
cropRect = CGRectMake(-rect.origin.x, | |
rect.origin.y, | |
rect.size.width, | |
rect.size.height) | |
} | |
// draw the image in the correct place | |
CGContextTranslateCTM(context, -cropRect!.origin.x, -cropRect!.origin.y) | |
CGContextDrawImage(context, | |
CGRectMake(0,0, size.width, size.height), | |
CGImage) | |
// and pull out the cropped image | |
let croppedImage = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return croppedImage | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment