Created
June 3, 2016 03:08
-
-
Save rosslebeau/34967db822c3571203cedf860cb832b1 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
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