Skip to content

Instantly share code, notes, and snippets.

@JayachandraA
Last active May 4, 2017 11:54
Show Gist options
  • Save JayachandraA/2c3dbd8f09d85dced28bfcc2dbe55c55 to your computer and use it in GitHub Desktop.
Save JayachandraA/2c3dbd8f09d85dced28bfcc2dbe55c55 to your computer and use it in GitHub Desktop.
extension UIImage {
/// Returns a image that fills in newSize
func resizedImage(newSize: CGSize) -> UIImage {
// Guard newSize is different
guard self.size != newSize else { return self }
UIGraphicsBeginImageContextWithOptions(newSize, false, 0.0);
self.draw(in: CGRect(x:0, y:0, width:newSize.width, height:newSize.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
/// Returns a resized image that fits in rectSize, keeping it's aspect ratio
/// Note that the new image size is not rectSize, but within it.
func resizedImageWithinRect(rectSize: CGSize) -> UIImage {
let widthFactor = size.width / rectSize.width
let heightFactor = size.height / rectSize.height
var resizeFactor = widthFactor
if size.height > size.width {
resizeFactor = heightFactor
}
let newSize = CGSize(width:size.width/resizeFactor, height:size.height/resizeFactor)
let resized = resizedImage(newSize: newSize)
return resized
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment