CGSize+Swift.swift 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. //
  2. // CGSize+Swift.swift
  3. // Haneke
  4. //
  5. // Created by Oriol Blanc Gimeno on 09/09/14.
  6. // Copyright (c) 2014 Haneke. All rights reserved.
  7. //
  8. import UIKit
  9. extension CGSize {
  10. func hnk_aspectFillSize(_ size: CGSize) -> CGSize {
  11. let scaleWidth = size.width / self.width
  12. let scaleHeight = size.height / self.height
  13. let scale = max(scaleWidth, scaleHeight)
  14. let resultSize = CGSize(width: self.width * scale, height: self.height * scale)
  15. return CGSize(width: ceil(resultSize.width), height: ceil(resultSize.height))
  16. }
  17. func hnk_aspectFitSize(_ size: CGSize) -> CGSize {
  18. let targetAspect = size.width / size.height
  19. let sourceAspect = self.width / self.height
  20. var resultSize = size
  21. if (targetAspect > sourceAspect) {
  22. resultSize.width = size.height * sourceAspect
  23. }
  24. else {
  25. resultSize.height = size.width / sourceAspect
  26. }
  27. return CGSize(width: ceil(resultSize.width), height: ceil(resultSize.height))
  28. }
  29. }