Skip to content

Instantly share code, notes, and snippets.

@foxicode
Created August 10, 2020 12:07
Show Gist options
  • Select an option

  • Save foxicode/ac73edec2e67279771fc43ad863e4a90 to your computer and use it in GitHub Desktop.

Select an option

Save foxicode/ac73edec2e67279771fc43ad863e4a90 to your computer and use it in GitHub Desktop.
Resizing UIImage keeping aspect ratio
import UIKit
extension UIImage {
func resized(maxSize: CGFloat) -> UIImage? {
let scale: CGFloat
if size.width > size.height {
scale = maxSize / size.width
}
else {
scale = maxSize / size.height
}
let newWidth = size.width * scale
let newHeight = size.height * scale
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment