Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The original code to resize UIImage
extension UIImage {
func resizedImage(newSize:CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
self.drawInRect(CGRectMake(0, 0, newSize.width, newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
/// Resize image, keep the aspect ratio
func resizedImageWithAspectFit(newSize:CGSize) -> UIImage {
// Resize with aspect
var resizeFactor = size.width / newSize.width
if size.height > size.width {
// But if height is bigger
resizeFactor = size.height / newSize.height
}
let newSizeFixedAspect = CGSizeMake(size.width/resizeFactor, size.height/resizeFactor)
let resized = resizedImage(newSizeFixedAspect)
return resized
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment