UIImage+Crop.swift 1.4 KB

12345678910111213141516171819202122232425262728293031323334
  1. //
  2. // UIImage+Crop.swift
  3. // CropViewController
  4. //
  5. // Created by Guilherme Moura on 2/26/16.
  6. // Copyright © 2016 Reefactor, Inc. All rights reserved.
  7. // Credit https://github.com/sprint84/PhotoCropEditor
  8. import UIKit
  9. extension UIImage {
  10. func rotatedImageWithTransform(_ rotation: CGAffineTransform, croppedToRect rect: CGRect) -> UIImage {
  11. let rotatedImage = rotatedImageWithTransform(rotation)
  12. let scale = rotatedImage.scale
  13. let cropRect = rect.applying(CGAffineTransform(scaleX: scale, y: scale))
  14. let croppedImage = rotatedImage.cgImage?.cropping(to: cropRect)
  15. let image = UIImage(cgImage: croppedImage!, scale: self.scale, orientation: rotatedImage.imageOrientation)
  16. return image
  17. }
  18. fileprivate func rotatedImageWithTransform(_ transform: CGAffineTransform) -> UIImage {
  19. UIGraphicsBeginImageContextWithOptions(size, true, scale)
  20. let context = UIGraphicsGetCurrentContext()
  21. context?.translateBy(x: size.width / 2.0, y: size.height / 2.0)
  22. context?.concatenate(transform)
  23. context?.translateBy(x: size.width / -2.0, y: size.height / -2.0)
  24. draw(in: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height))
  25. let rotatedImage = UIGraphicsGetImageFromCurrentImageContext()
  26. UIGraphicsEndImageContext()
  27. return rotatedImage!
  28. }
  29. }