Last active
September 18, 2021 04:01
-
-
Save jkereako/200342b66b5416fd715a to your computer and use it in GitHub Desktop.
A Swift version of this SO answer: http://stackoverflow.com/questions/603907/uiimage-resize-then-crop#605385
This file contains hidden or 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
// credit: http://stackoverflow.com/questions/603907/uiimage-resize-then-crop#605385 | |
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 = CGPoint.zero | |
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 = CGRect.zero | |
thumbnailRect.origin = thumbnailOrigin | |
thumbnailRect.size.width = scaledWidth | |
thumbnailRect.size.height = scaledHeight | |
// Why use `UIGraphicsBeginImageContextWithOptions` over `UIGraphicsBeginImageContext`? | |
// see: http://stackoverflow.com/questions/4334233/how-to-capture-uiview-to-uiimage-without-loss-of-quality-on-retina-display#4334902 | |
UIGraphicsBeginImageContextWithOptions(size, false, 0.0) | |
image.draw(in: thumbnailRect) | |
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()! | |
UIGraphicsEndImageContext() | |
return scaledImage | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks man! it solved my big problem!