Skip to content

Instantly share code, notes, and snippets.

@lacyrhoades
Created April 18, 2018 15:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lacyrhoades/a7b709e7c6c3702330efdc4c0d60a044 to your computer and use it in GitHub Desktop.
Save lacyrhoades/a7b709e7c6c3702330efdc4c0d60a044 to your computer and use it in GitHub Desktop.
extension UIImage {
func imageCenterCroppedTo(cropSize: CGSize) -> UIImage {
let cropWidth: CGFloat = cropSize.width // 200
let cropHeight: CGFloat = cropSize.height // 200
let cropRatio = cropWidth / cropHeight
let naturalRatio = self.size.width / self.size.height
var scaledWidth = cropWidth
var scaledHeight = cropHeight
var xOffset: CGFloat = 0
var yOffset: CGFloat = 0
if cropRatio > naturalRatio {
// fit width
scaledHeight = scaledWidth / naturalRatio
yOffset = -1 * abs(scaledHeight - cropHeight) / 2.0
} else {
// fit height
scaledWidth = scaledHeight * naturalRatio
xOffset = -1 * abs(scaledWidth - cropWidth) / 2.0
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: cropWidth, height: cropHeight), false, self.scale);
self.draw(in: CGRect(x: xOffset, y: yOffset, width: ceil(scaledWidth), height: ceil(scaledHeight)))
let croppedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return croppedImage!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment