Last active
December 20, 2020 21:41
-
-
Save sharplet/44bad5a45b266309f9e1b905588f8d90 to your computer and use it in GitHub Desktop.
Create an image thumbnail with an aspect fill resize mode
This file contains hidden or 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
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