Skip to content

Instantly share code, notes, and snippets.

@daltonclaybrook
Last active October 4, 2017 21:15
Show Gist options
  • Select an option

  • Save daltonclaybrook/77b1e5f41226e1a7fb9190f7cd2b7e86 to your computer and use it in GitHub Desktop.

Select an option

Save daltonclaybrook/77b1e5f41226e1a7fb9190f7cd2b7e86 to your computer and use it in GitHub Desktop.
extension UIImage {
func scaleFactorFor(maxSize: CGSize) -> CGFloat {
let imageSize = self.size
guard imageSize.width > maxSize.width || imageSize.height > maxSize.height else {
// image is already smaller than max
return 1.0
}
let widthScaleFactor = maxSize.width / imageSize.width
let heightScaleFactor = maxSize.height / imageSize.height
return min(widthScaleFactor, heightScaleFactor)
}
func scaledBy(factor: CGFloat) -> UIImage? {
guard factor != 1.0 else { return self }
let scaledSize = CGSize(width: self.size.width * factor, height: self.size.height * factor)
UIGraphicsBeginImageContextWithOptions(scaledSize, true, self.scale)
draw(in: CGRect(origin: .zero, size: scaledSize))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment