Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
extension CGSize {
func scaled(byFactor: CGFloat) -> CGSize {
return CGSize(width: width*byFactor, height: height*byFactor)
}
}
func scaleAndCropImage(image: UIImage, toSize size: CGSize, fitImage: Bool = true) -> UIImage {
guard image.size != size else { return image }
// Calculate scale factor for fit or fill
let (widthFactor, heightFactor) = (size.width / image.size.width, size.height / image.size.height)
let scaleFactor = fitImage ? min(widthFactor, heightFactor) : max(widthFactor, heightFactor)
// Establish drawing destination, which may start outside the drawing context bounds
let scaledSize = image.size.scaled(scaleFactor)
let drawingOrigin = CGPoint(x: (size.width - scaledSize.width) / 2.0, y: (size.height - scaledSize.height) / 2.0)
// Perform drawing and return image
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
let scaledImage: UIImage
do {
UIColor.blackColor().setFill(); UIRectFill(CGRect(origin: .zero, size: size))
image.drawInRect(CGRect(origin: drawingOrigin, size: scaledSize))
// Fetch image
scaledImage = UIGraphicsGetImageFromCurrentImageContext()!
}
UIGraphicsEndImageContext()
return scaledImage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.