Skip to content

Instantly share code, notes, and snippets.

@kylehowells
Last active July 2, 2022 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kylehowells/27e6e1bf42f283d22c3ae8bb9faaeece to your computer and use it in GitHub Desktop.
Save kylehowells/27e6e1bf42f283d22c3ae8bb9faaeece to your computer and use it in GitHub Desktop.
import CoreGraphics
import UIKit
import AVFoundation
extension UIImage {
func resized(within newSize: CGSize, outputScale: CGFloat? = nil) -> UIImage {
let originalSize = self.size
let withinBounds = CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)
var newFrame = AVMakeRect(aspectRatio: originalSize, insideRect: withinBounds)
newFrame.origin = CGPoint.zero
let format = UIGraphicsImageRendererFormat.preferred()
if let scale = outputScale {
format.scale = scale
}
let renderer = UIGraphicsImageRenderer(size: newFrame.size, format: format)
let image = renderer.image(actions: { context in
self.draw(in: newFrame)
})
return image
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment