Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
// credit:
func scaleAndCropImage(_ image:UIImage, toSize size: CGSize) -> UIImage {
// Make sure the image isn't already sized.
guard !image.size.equalTo(size) else {
return image
let widthFactor = size.width / image.size.width
let heightFactor = size.height / image.size.height
var scaleFactor: CGFloat = 0.0
scaleFactor = heightFactor
if widthFactor > heightFactor {
scaleFactor = widthFactor
var thumbnailOrigin =
let scaledWidth = image.size.width * scaleFactor
let scaledHeight = image.size.height * scaleFactor
if widthFactor > heightFactor {
thumbnailOrigin.y = (size.height - scaledHeight) / 2.0
else if widthFactor < heightFactor {
thumbnailOrigin.x = (size.width - scaledWidth) / 2.0
var thumbnailRect =
thumbnailRect.origin = thumbnailOrigin
thumbnailRect.size.width = scaledWidth
thumbnailRect.size.height = scaledHeight
// Why use `UIGraphicsBeginImageContextWithOptions` over `UIGraphicsBeginImageContext`?
// see:
UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
image.draw(in: thumbnailRect)
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()!
return scaledImage
Copy link

jkereako commented Jan 17, 2016


This resizes and then crops an image to fit within a specified rect.

The image is drawn off-screen in a buffer, that is done with UIGraphicsBeginImageContextWithOptions. See the Drawing and Printing Guide for iOS


Although this is the most efficient way to resize an image it still is an expensive procedure, hence, it ought to be run a few times as possible. Execute this routine on a background thread and then cache the result.

Copy link

SasanBaho commented Apr 9, 2020

Thanks man! it solved my big problem!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment