Skip to content

Instantly share code, notes, and snippets.

@dkw5877
Created March 28, 2019 17:19
Show Gist options
  • Select an option

  • Save dkw5877/35d7598a929d96ef284ed7aa9681bf80 to your computer and use it in GitHub Desktop.

Select an option

Save dkw5877/35d7598a929d96ef284ed7aa9681bf80 to your computer and use it in GitHub Desktop.
Example of using AVFoundation's AVMakeRect to resize and image
/* create the image at original size */
let image = UIImage(named: "Landscape-1276x800.jpg")!
/*
* create bounding rect with largest possible height based on width
* this will get you the aspect height for the speficied width
*/
let boundingRect = CGRect(x: 0, y: 0, width: 300, height:CGFloat.greatestFiniteMagnitude)
/*
* Returns a scaled CGRect that maintains the aspect ratio specified
* by a CGSize within a bounding CGRect
*/
let aspectRect = AVMakeRect(aspectRatio: image1.size, insideRect: boundingRect)
/* create a UIGraphicsImageRenderer to draw the image */
let renderer = UIGraphicsImageRenderer(size: aspectRect.size)
/*
WARNING be careful about the origin points, if the result of the calculation is an exponential value like
8.988465674311579e+307, then the image won't draw. To be safe I set the origin to .zero
*/
let img = renderer.image { (context) in
image.draw(in: CGRect(origin: .zero, size: aspectRect.size))
}
@mapedd

mapedd commented Nov 4, 2022

Copy link
Copy Markdown

this is great snippet!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment