Skip to content

Instantly share code, notes, and snippets.

@heestand-xyz
Last active November 20, 2019 07:04
Show Gist options
  • Save heestand-xyz/6fdd3da818680a25cc8d114c884f72c0 to your computer and use it in GitHub Desktop.
Save heestand-xyz/6fdd3da818680a25cc8d114c884f72c0 to your computer and use it in GitHub Desktop.
Image Resize - Aspect Fit / Fill
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!
}
@ham118
Copy link

ham118 commented Nov 20, 2019

Thanks for sharing! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment