title: Cropping a captured image exactly to how it looks in AVCaptureVideoPreviewLayer
body: <p>I have a photo app that is using AV Foundation. I have setup a preview layer using AVCaptureVideoPreviewLayer that takes up the top half of the screen. So when the user is trying to take their photo, all they can see is what the top half of the screen sees.</p>
  
  <p>This works great, but when the user actually takes the photo and I try to set the photo as the layer's contents, the image is distorted. I did research and realized that I would need to crop the image.</p>
  
  <p>All I want to do is crop the full captured image so that all that is left is exactly what the user could originally see in the top half of the screen.</p>
  
  <p>I have been able to sort-of accomplish this but I am doing this by entering in manual CGRect values and it still does not look perfect. There has to be an easier way to do this.</p>
  
  <p>I have literally gone through every post on stack overflow for the past 2 days about cropping images and nothing has worked.</p>
  
  <p>There has to be a way to programmatically crop the captured image so that the final image will be exactly what was originally seen in the preview layer.</p>
  
  <p>Here is my viewDidLoad implementation:</p>
  
  <pre><code>- (void)viewDidLoad
  {
      [super viewDidLoad];
  
      AVCaptureSession *session =[[AVCaptureSession alloc]init];
      [session setSessionPreset:AVCaptureSessionPresetPhoto];
  
      AVCaptureDevice *inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  
      NSError *error = [[NSError alloc]init];
      AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&amp;error];
  
      if([session canAddInput:deviceInput])
          [session addInput:deviceInput];
  
      CALayer *rootLayer = [[self view]layer];
      [rootLayer setMasksToBounds:YES];
  
      _previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:session];
      [_previewLayer setFrame:CGRectMake(0, 0, rootLayer.bounds.size.width, rootLayer.bounds.size.height/2)];
      [_previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
  
      [rootLayer insertSublayer:_previewLayer atIndex:0];
  
      _stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
      [session addOutput:_stillImageOutput];
  
      [session startRunning];
      }
  </code></pre>
  
  <p>And here is the code that runs when the user presses the button to capture a photo:</p>
  
  <pre><code>-(IBAction)stillImageCapture {
      AVCaptureConnection *videoConnection = nil;
      for (AVCaptureConnection *connection in _stillImageOutput.connections){
          for (AVCaptureInputPort *port in [connection inputPorts]){
              if ([[port mediaType] isEqual:AVMediaTypeVideo]){
                  videoConnection = connection;
                  break;
              }
          }
          if (videoConnection) {
              break;
          }
      }
  
      NSLog(@"about to request a capture from: %@", _stillImageOutput);
  
      [_stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
          if(imageDataSampleBuffer) {
              NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
  
              UIImage *image = [[UIImage alloc]initWithData:imageData];
              CALayer *subLayer = [CALayer layer];
              subLayer.frame = _previewLayer.frame;
              image = [self rotate:image andOrientation:image.imageOrientation];
  
              //Below is the crop that is sort of working for me, but as you can see I am manually entering in values and just guessing and it still does not look perfect.
              CGRect cropRect = CGRectMake(0, 650, 3000, 2000);
              CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], cropRect);
  
              subLayer.contents = (id)[UIImage imageWithCGImage:imageRef].CGImage;
              subLayer.frame = _previewLayer.frame;
  
              [_previewLayer addSublayer:subLayer];
          }
      }];
  }
  </code></pre>