Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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 =
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