0

I want to implement a view controller that can crop an image using the frame of the red CGRect. I tried the following code but it seems like my cropping logic is way off. The cropped image seems to be a tiny portion of the original image... How can I grab an UIImage of just whatever inside my red rectangle CGRect?

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        picker.dismiss(animated: true, completion: nil)

        if let x = info[UIImagePickerControllerOriginalImage] as? UIImage {
            let a = x.cgImage?.cropping(to: CGRect(x: 100, y: 100, width: 200, height: 50))
            let b = UIImage(cgImage: a!)
            let y = UIImageView(frame: self.view.frame)
            y.image = b 
            self.view.addSubview(y)
        }
    }

enter image description here

7ball
  • 2,183
  • 4
  • 26
  • 61
  • 1
    You need to know the CGRect of the crop area in terms of the _image_, not just the image _view_. You have to know how the image is being displayed within the image view. The original image is _much_ larger than what is being displayed. So if you crop to the size of the rectangle being displayed, you crop a much _smaller_ piece of the original image. – matt Aug 23 '17 at 01:49
  • Hi @matt thanks for replying. Can you elaborate a little bit more on your answer? – 7ball Aug 23 '17 at 01:51
  • What part of it don't you understand? It's a simple arithmetic fact. Unless you know both the size of the original image and the size to which it is being scaled down for display, you cannot crop successfully. You asked why you were ending up with only a tiny portion of the image and I explained that. Perfectly. – matt Aug 23 '17 at 01:55
  • Ok your edited comment confirms my theory. I did some more logging and could see that the image capture is 3024x4032.. This ratio doesn't translate well to the size of my camera preview View, which at full screen, is 375x667. I thought I could just scale the image down and apply the CGRect that way, but it doesn't seem like that would work? – 7ball Aug 23 '17 at 02:03
  • The problem is that you don't know _how_ to scale the image down because you don't know how it is being displayed to you. See my answer in the duplicate. I can solve the problem there because _I_ am in charge of the image view that is showing the image to be cropped, so I _know_ how it is being scaled. – matt Aug 23 '17 at 02:16
  • Downloadable project here: https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch02p058cropImageView/Cropper/ViewController.swift – matt Aug 23 '17 at 02:29

0 Answers0