CGRect+Utils.swift 995 B

123456789101112131415161718192021222324252627
  1. //
  2. // CGRect+Utils.swift
  3. // WeScan
  4. //
  5. // Created by Boris Emorine on 2/26/18.
  6. // Copyright © 2018 WeTransfer. All rights reserved.
  7. //
  8. import Foundation
  9. extension CGRect {
  10. /// Returns a new `CGRect` instance scaled up or down, with the same center as the original `CGRect` instance.
  11. /// - Parameters:
  12. /// - ratio: The ratio to scale the `CGRect` instance by.
  13. /// - Returns: A new instance of `CGRect` scaled by the given ratio and centered with the original rect.
  14. func scaleAndCenter(withRatio ratio: CGFloat) -> CGRect {
  15. let scaleTransform = CGAffineTransform(scaleX: ratio, y: ratio)
  16. let scaledRect = applying(scaleTransform)
  17. let translateTransform = CGAffineTransform(translationX: origin.x * (1 - ratio) + (width - scaledRect.width) / 2.0, y: origin.y * (1 - ratio) + (height - scaledRect.height) / 2.0)
  18. let translatedRect = scaledRect.applying(translateTransform)
  19. return translatedRect
  20. }
  21. }