Last active
May 4, 2017 11:54
-
-
Save JayachandraA/2c3dbd8f09d85dced28bfcc2dbe55c55 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
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