Advertisement
srk72

Crope image

Jan 12th, 2022
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.29 KB | None | 0 0
  1. func cropToBounds(image: UIImage, height: CGFloat, width: CGFloat, view: Int) -> UIImage {
  2.  
  3. let cgimage = image.cgImage!
  4. let contextImage: UIImage = UIImage(cgImage: cgimage)
  5. // let contextSize: CGSize = contextImage.size
  6. var posX: CGFloat = 0.0
  7. var posY: CGFloat = 0.0
  8. var cgwidth: CGFloat = CGFloat()
  9. var cgheight: CGFloat = CGFloat()
  10. var viewHeight = CGFloat()
  11. var viewWidth = CGFloat()
  12.  
  13. if view == 1 {
  14. viewHeight = imageView1.frame.height
  15. viewWidth = imageView1.frame.width
  16. } else if view == 2 {
  17. viewHeight = imageView2.frame.height
  18. viewWidth = imageView2.frame.width
  19. } else if view == 3 {
  20. viewHeight = imageView3.frame.height
  21. viewWidth = imageView3.frame.width
  22. } else if view == 4 {
  23. viewHeight = imageView4.frame.height
  24. viewWidth = imageView4.frame.width
  25. }
  26.  
  27. // See what size is longer and create the center off of that
  28.  
  29. if viewWidth > viewHeight && height > width {
  30.  
  31. posX = height / 2
  32. posY = width / 2
  33. cgwidth = width
  34. cgheight = viewHeight * 1.2
  35.  
  36. } else if viewHeight > viewWidth && width > height {
  37. posX = height / 2
  38. posY = width / 2
  39. cgwidth = viewWidth * 1.2
  40. cgheight = height
  41. }
  42.  
  43.  
  44. // if width > height {
  45. // posX = ((width - height) / 2)
  46. // posY = 0
  47. // cgwidth = width * 0.6
  48. // cgheight = height
  49. // } else {
  50. // posX = 0
  51. // posY = ((height - width) / 2)
  52. // cgwidth = width
  53. // cgheight = height
  54. // }
  55.  
  56. let rect: CGRect = CGRect(x: posX, y: posY, width: cgwidth, height: cgheight)
  57.  
  58. // Create bitmap image from context using the rect
  59. let imageRef: CGImage = cgimage.cropping(to: rect)!
  60.  
  61. // Create a new image based on the imageRef and rotate back to the original orientation
  62. let image: UIImage = UIImage(cgImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
  63.  
  64. return image
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement