UIImageView+Extension.swift 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. //
  2. // UIImageView+Extension.swift
  3. // O2Platform
  4. //
  5. // Created by FancyLou on 2019/10/30.
  6. // Copyright © 2019 zoneland. All rights reserved.
  7. //
  8. import UIKit
  9. extension UIImageView {
  10. func o2AspectToFitFrame() -> CGRect {
  11. guard let image = image else {
  12. assertionFailure("No image found!")
  13. return CGRect.zero
  14. }
  15. let imageRatio: CGFloat = image.size.width / image.size.height
  16. let viewRatio: CGFloat = frame.size.width / frame.size.height
  17. if imageRatio < viewRatio {
  18. let scale: CGFloat = frame.size.height / image.size.height
  19. let width: CGFloat = scale * image.size.width
  20. let topLeftX: CGFloat = (frame.size.width - width) * 0.5
  21. return CGRect(x: topLeftX, y: 0, width: width, height: frame.size.height)
  22. } else {
  23. let scale: CGFloat = frame.size.width / image.size.width
  24. let height: CGFloat = scale * image.size.height
  25. let topLeftY: CGFloat = (frame.size.height - height) * 0.5
  26. return CGRect(x: 0, y: topLeftY, width: frame.size.width, height: height)
  27. }
  28. }
  29. }