Created
February 23, 2020 18:20
-
-
Save nbertagnolli/eb82d914442a86f4cbb36dcaac2f943c to your computer and use it in GitHub Desktop.
Resize Image in Swift3
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
// Create a variable describing the desired dimensions of our image | |
private let trainedImageSize = CGSize(width: 64, height: 64) | |
// Taken from: | |
// https://stackoverflow.com/questions/31314412/how-to-resize-image-in-swift | |
func resizeImage(image: UIImage, targetSize: CGSize) -> UIImage { | |
let size = image.size | |
let widthRatio = targetSize.width / size.width | |
let heightRatio = targetSize.height / size.height | |
// Figure out what our orientation is, and use that to form the rectangle | |
var newSize: CGSize | |
if(widthRatio > heightRatio) { | |
newSize = CGSize(width: size.width * heightRatio, height: size.height * heightRatio) | |
} else { | |
newSize = CGSize(width: size.width * widthRatio, height: size.height * widthRatio) | |
} | |
// This is the rect that we've calculated out and this is what is actually used below | |
let rect = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height) | |
// Actually do the resizing to the rect using the ImageContext stuff | |
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0) | |
image.draw(in: rect) | |
let newImage = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return newImage! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment