Created
June 12, 2018 02:51
-
-
Save bob910078/2971d13d759f17d6bb3b8ebaeb783a08 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
func cropToSquare(image: UIImage) -> UIImage? { | |
if let cgImg = image.cgImage { | |
let contextSize: CGSize = image.size | |
var posX: CGFloat = 0 | |
var posY: CGFloat = 0 | |
var length: CGFloat = 0 | |
if contextSize.width > contextSize.height { | |
posX = (contextSize.width - contextSize.height) / 2 | |
posY = 0 | |
length = contextSize.height | |
} else { | |
posX = 0 | |
posY = ((contextSize.height - contextSize.width) / 2) | |
length = contextSize.width | |
} | |
let rect = CGRect(x: posX, y: posY, width: length, height: length) | |
// Create bitmap image from context using the rect | |
guard let imageRef: CGImage = cgImg.cropping(to: rect) else { | |
return nil | |
} | |
// Create a new image based on the imageRef and rotate back to the original orientation | |
let image = UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation) | |
return image | |
} else { | |
// convert failure | |
return nil | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment