Created
April 29, 2015 09:42
-
-
Save axldyb/9839c003e77701d1e7d1 to your computer and use it in GitHub Desktop.
Extension for cropping an UIImage to a square.
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 cropsToSquare() -> UIImage { | |
let refWidth = CGFloat(CGImageGetWidth(self.CGImage)) | |
let refHeight = CGFloat(CGImageGetHeight(self.CGImage)) | |
let cropSize = refWidth > refHeight ? refHeight : refWidth | |
let x = (refWidth - cropSize) / 2.0 | |
let y = (refHeight - cropSize) / 2.0 | |
let cropRect = CGRectMake(x, y, cropSize, cropSize) | |
let imageRef = CGImageCreateWithImageInRect(self.CGImage, cropRect) | |
let cropped = UIImage(CGImage: imageRef, scale: 0.0, orientation: self.imageOrientation)! | |
return cropped | |
} | |
} |
Doesn't crash when passed a nil image:
extension UIImage {
func cropsToSquare() -> UIImage? {
if let image = self.cgImage {
let refWidth = CGFloat((image.width))
let refHeight = CGFloat((image.height))
let cropSize = refWidth > refHeight ? refHeight : refWidth
let x = (refWidth - cropSize) / 2.0
let y = (refHeight - cropSize) / 2.0
let cropRect = CGRect(x: x, y: y, width: cropSize, height: cropSize)
let imageRef = image.cropping(to: cropRect)
let cropped = UIImage(cgImage: imageRef!, scale: 0.0, orientation: self.imageOrientation)
return cropped
}
return nil
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Swift 4 Version :