Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. extension UIImage {
  2. enum AspectOrientation {
  3. case portrait
  4. case square
  5. case landscape
  6. }
  7.  
  8. var aspectRatio: CGFloat {
  9. return size.aspectRatio
  10. }
  11.  
  12. var aspectOrientation: AspectOrientation {
  13. if aspectRatio > 1 {
  14. return .landscape
  15. } else if aspectRatio < 1 {
  16. return .portrait
  17. } else {
  18. return .square
  19. }
  20. }
  21.  
  22. func resizeAspectFill(to destinationSize: CGSize) -> UIImage {
  23. let canvas = CGRect(origin: .zero, size: destinationSize)
  24.  
  25. return UIGraphicsImageRenderer(bounds: canvas).image { _ in
  26. let transform: CGAffineTransform
  27.  
  28. switch aspectOrientation {
  29. case .portrait:
  30. let scale = destinationSize.width / size.width
  31. let height = size.height * scale
  32. let translation = CGAffineTransform(translationX: 0, y: (destinationSize.height - height) / 2)
  33. transform = CGAffineTransform(scaleX: scale, y: scale).concatenating(translation)
  34.  
  35. case .landscape:
  36. let scale = destinationSize.height / size.height
  37. let width = size.width * scale
  38. let translation = CGAffineTransform(translationX: (destinationSize.width - width) / 2, y: 0)
  39. transform = CGAffineTransform(scaleX: scale, y: scale).concatenating(translation)
  40.  
  41. case .square:
  42. let scale = destinationSize.width / size.width
  43. transform = CGAffineTransform(scaleX: scale, y: scale)
  44. }
  45.  
  46. let aspectFillBounds = CGRect(origin: .zero, size: size).applying(transform)
  47. draw(in: aspectFillBounds)
  48. }
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement