Skip to content

Instantly share code, notes, and snippets.

@samwize
Created June 1, 2016 06:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save samwize/d7b9ef1bb8b9a66406af9dca1bd3b207 to your computer and use it in GitHub Desktop.
Save samwize/d7b9ef1bb8b9a66406af9dca1bd3b207 to your computer and use it in GitHub Desktop.
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