Created
April 18, 2018 15:28
-
-
Save lacyrhoades/a7b709e7c6c3702330efdc4c0d60a044 to your computer and use it in GitHub Desktop.
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 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