Last active
November 20, 2019 07:04
-
-
Save heestand-xyz/6fdd3da818680a25cc8d114c884f72c0 to your computer and use it in GitHub Desktop.
Image Resize - Aspect Fit / Fill
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
public enum ImagePlacement { | |
case fill | |
case fit | |
} | |
public static func resize(_ image: UIImage, to size: CGSize, placement: ImagePlacement = .fill) -> UIImage { | |
let frame: CGRect | |
switch placement { | |
case .fit: | |
frame = CGRect( | |
x: image.size.width / size.width > image.size.height / size.height ? | |
0 : (size.width - image.size.width * (size.height / image.size.height)) / 2, | |
y: image.size.width / size.width < image.size.height / size.height ? | |
0 : (size.height - image.size.height * (size.width / image.size.width)) / 2, | |
width: image.size.width / size.width > image.size.height / size.height ? | |
size.width : image.size.width * (size.height / image.size.height), | |
height: image.size.width / size.width < image.size.height / size.height ? | |
size.height : image.size.height * (size.width / image.size.width) | |
) | |
case .fill: | |
frame = CGRect( | |
x: image.size.width / size.width < image.size.height / size.height ? | |
0 : (size.width - image.size.width * (size.height / image.size.height)) / 2, | |
y: image.size.width / size.width > image.size.height / size.height ? | |
0 : (size.height - image.size.height * (size.width / image.size.width)) / 2, | |
width: image.size.width / size.width < image.size.height / size.height ? | |
size.width : image.size.width * (size.height / image.size.height), | |
height: image.size.width / size.width > image.size.height / size.height ? | |
size.height : image.size.height * (size.width / image.size.width) | |
) | |
} | |
UIGraphicsBeginImageContext(size) | |
image.draw(in: frame) | |
let resized_image = UIGraphicsGetImageFromCurrentImageContext() | |
UIGraphicsEndImageContext() | |
return resized_image! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for sharing! 👍