Skip to content

Instantly share code, notes, and snippets.

@axldyb
Created April 29, 2015 09:42
Show Gist options
  • Save axldyb/9839c003e77701d1e7d1 to your computer and use it in GitHub Desktop.
Save axldyb/9839c003e77701d1e7d1 to your computer and use it in GitHub Desktop.
Extension for cropping an UIImage to a square.
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
}
}
@jacobwhite
Copy link

jacobwhite commented Jan 11, 2022

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