Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement