Skip to content

Instantly share code, notes, and snippets.

@gorillka
Forked from foxicode/UIImage+resized.swift
Created August 21, 2020 05:56
Show Gist options
  • Save gorillka/a18a98e13eca4e46b127d9514a3f676b to your computer and use it in GitHub Desktop.
Save gorillka/a18a98e13eca4e46b127d9514a3f676b 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