UIImage+Utils.swift 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. //
  2. // UIImage+Utils.swift
  3. // WeScan
  4. //
  5. // Created by Bobo on 5/25/18.
  6. // Copyright © 2018 WeTransfer. All rights reserved.
  7. //
  8. import Foundation
  9. extension UIImage {
  10. /// Draws a new cropped and scaled (zoomed in) image.
  11. ///
  12. /// - Parameters:
  13. /// - point: The center of the new image.
  14. /// - scaleFactor: Factor by which the image should be zoomed in.
  15. /// - size: The size of the rect the image will be displayed in.
  16. /// - Returns: The scaled and cropped image.
  17. func scaledImage(atPoint point: CGPoint, scaleFactor: CGFloat, targetSize size: CGSize) -> UIImage? {
  18. guard let cgImage = self.cgImage else {
  19. return nil
  20. }
  21. let scaledSize = CGSize(width: size.width / scaleFactor, height: size.height / scaleFactor)
  22. guard let croppedImage = cgImage.cropping(to: CGRect(x: point.x - scaledSize.width / 2.0, y: point.y - scaledSize.height / 2.0, width: scaledSize.width, height: scaledSize.height)) else {
  23. return nil
  24. }
  25. return UIImage(cgImage: croppedImage)
  26. }
  27. }