Skip to content

Instantly share code, notes, and snippets.

@sharplet
Last active December 20, 2020 21:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharplet/44bad5a45b266309f9e1b905588f8d90 to your computer and use it in GitHub Desktop.
Save sharplet/44bad5a45b266309f9e1b905588f8d90 to your computer and use it in GitHub Desktop.
Create an image thumbnail with an aspect fill resize mode
extension UIImage {
enum AspectOrientation {
case portrait
case square
case landscape
}
var aspectRatio: CGFloat {
return size.aspectRatio
}
var aspectOrientation: AspectOrientation {
if aspectRatio > 1 {
return .landscape
} else if aspectRatio < 1 {
return .portrait
} else {
return .square
}
}
func resizeAspectFill(to destinationSize: CGSize) -> UIImage {
let canvas = CGRect(origin: .zero, size: destinationSize)
return UIGraphicsImageRenderer(bounds: canvas).image { _ in
let transform: CGAffineTransform
switch aspectOrientation {
case .portrait:
let scale = destinationSize.width / size.width
let height = size.height * scale
let translation = CGAffineTransform(translationX: 0, y: (destinationSize.height - height) / 2)
transform = CGAffineTransform(scaleX: scale, y: scale).concatenating(translation)
case .landscape:
let scale = destinationSize.height / size.height
let width = size.width * scale
let translation = CGAffineTransform(translationX: (destinationSize.width - width) / 2, y: 0)
transform = CGAffineTransform(scaleX: scale, y: scale).concatenating(translation)
case .square:
let scale = destinationSize.width / size.width
transform = CGAffineTransform(scaleX: scale, y: scale)
}
let aspectFillBounds = CGRect(origin: .zero, size: size).applying(transform)
draw(in: aspectFillBounds)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment