Advertisement
srk72

Batter Cropping image

Feb 11th, 2022
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. // Crop image for Horizontal Collection Cell imageView
  2. func cropToBounds(image: UIImage, height: CGFloat, width: CGFloat) -> UIImage {
  3.  
  4. let cgimage = image.cgImage!
  5. var posX: CGFloat = 0.0
  6. var posY: CGFloat = 0.0
  7. let contextImage: UIImage = UIImage(cgImage: cgimage)
  8. let contextSize: CGSize = contextImage.size
  9. var cgwidth: CGFloat = CGFloat(width)
  10. var cgheight: CGFloat = CGFloat(height)
  11.  
  12. if contextSize.height > contextSize.width {
  13. cgwidth = contextSize.width * 0.8
  14. cgheight = contextSize.height * 0.5
  15. posX = (contextSize.width * 0.1)
  16. posY = (contextSize.height * 0.2)
  17. } else if contextSize.width > contextSize.height {
  18. cgwidth = contextSize.width * 0.8
  19. cgheight = contextSize.height
  20. posX = (contextSize.width * 0.1)
  21. posY = 0
  22. } else {
  23. return image
  24. }
  25.  
  26. let rect: CGRect = CGRect(x: posX, y: posY, width: cgwidth, height: cgheight)
  27.  
  28. // Create bitmap image from context using the rect
  29. let imageRef: CGImage = cgimage.cropping(to: rect)!
  30.  
  31. // Create a new image based on the imageRef and rotate back to the original orientation
  32. let image: UIImage = UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
  33.  
  34. return image
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement