Skip to content

Instantly share code, notes, and snippets.

@Bogidon
Created March 31, 2017 19:36
Show Gist options
  • Save Bogidon/e5945dc52af131036f3f25120f654701 to your computer and use it in GitHub Desktop.
Save Bogidon/e5945dc52af131036f3f25120f654701 to your computer and use it in GitHub Desktop.
Scale and fit an image in a size
extension UIImage {
/// Aspect fit an image from a size. (center)
///
/// The input size is the minimum size of the output image. The size of `self` is the
/// maximum size of the output image. Aspect ratio is maintained. Transparency is added to the
/// sides of the output image to keep the image centered.
///
/// - parameter in: The `CGSize` in which to scale and center `self`.
func scaleAndFit(in inputSize: CGSize) -> UIImage? {
// Scale rect to fit image, if image is larger.
// E.g. image 6000x4000, rect 200x400, results in 6000 x 12000
let scaledSize: CGSize = {
let ratio = (size.height > size.width) ?
max(size.height / inputSize.height, 1.0):
max(size.width / inputSize.width, 1.0)
return CGSize(width: inputSize.width*ratio, height: inputSize.height*ratio)
}()
// Fit image inside scaled rect
// E.g. image 6000x4000, scaled rect 6000x12000, results in (0, 4000, 6000, 4000)
let scaledAspectFitRect = AVMakeRect(aspectRatio: size, insideRect: CGRect(origin: .zero, size: scaledSize))
// Create the image
UIGraphicsBeginImageContextWithOptions(scaledSize, false, 0.0)
draw(in: scaledAspectFitRect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment