Created
March 28, 2019 17:19
-
-
Save dkw5877/35d7598a929d96ef284ed7aa9681bf80 to your computer and use it in GitHub Desktop.
Example of using AVFoundation's AVMakeRect to resize and image
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
this is great snippet!