Skip to content

Instantly share code, notes, and snippets.

@rosslebeau
Created June 3, 2016 03:08
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 rosslebeau/34967db822c3571203cedf860cb832b1 to your computer and use it in GitHub Desktop.
Save rosslebeau/34967db822c3571203cedf860cb832b1 to your computer and use it in GitHub Desktop.
func scaleAndCropImage(_ image: UIImage, toSize newSize: CGSize) -> UIImage {
if image.size.equalTo(newSize) {
return image
}
// Find the ratios of the desired dimensions to the current dimensions,
// and use the larger one to scale the image to fill the desired size
let widthFactor = newSize.width / image.size.width
let heightFactor = newSize.height / image.size.height
let scaleFactor = max(widthFactor, heightFactor)
let scaledSize = CGSize(width: image.size.width * scaleFactor, height: image.size.height * scaleFactor)
// Inset the origin to draw from so that the intersection of the new size and scaled size will be centered
let drawingOrigin = CGPoint(x: (newSize.width - scaledSize.width) / 2.0, y: (newSize.height - scaledSize.height) / 2.0)
let drawingRect = CGRect(origin: drawingOrigin, size: scaledSize)
// Passing an image context scale of 0.0 results in a scale equal to the screen's scale
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0)
image.draw(in: drawingRect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return scaledImage
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment