UIImageExtension.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // UIImageExtension.swift
  3. // LoopFollow
  4. //
  5. // Created by Jon Fawcett on 10/6/20.
  6. // Copyright © 2020 Jon Fawcett. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. extension UIImage {
  11. func resizeImage(_ dimension: CGFloat, landscape: Bool, opaque: Bool, contentMode: UIView.ContentMode = .scaleAspectFit) -> UIImage {
  12. var width: CGFloat
  13. var height: CGFloat
  14. var newImage: UIImage
  15. let size = self.size
  16. let aspectRatio = size.width/size.height
  17. switch contentMode {
  18. case .scaleAspectFit:
  19. if landscape { // Landscape image
  20. width = dimension
  21. height = dimension / aspectRatio
  22. } else { // Portrait image
  23. height = dimension
  24. width = dimension * aspectRatio
  25. }
  26. default:
  27. width = 368.0
  28. height = 448.0
  29. }
  30. if #available(iOS 10.0, *) {
  31. let renderFormat = UIGraphicsImageRendererFormat.default()
  32. renderFormat.opaque = opaque
  33. let renderer = UIGraphicsImageRenderer(size: CGSize(width: width, height: height), format: renderFormat)
  34. newImage = renderer.image {
  35. (context) in
  36. self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
  37. }
  38. } else {
  39. UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), opaque, 0)
  40. self.draw(in: CGRect(x: 0, y: 0, width: width, height: height))
  41. newImage = UIGraphicsGetImageFromCurrentImageContext()!
  42. UIGraphicsEndImageContext()
  43. }
  44. return newImage
  45. }
  46. }