title: Crop Image using CGRect
body: <p>I have been trying to do this since forever. I have a camera overlay. I want to get my final image to be the part of the image viewable from the in-built camera.
  What I did was make  CGRect with dimensions equal to the square in the camera. Then I tried cropping it using this function.</p>
  
  <pre><code>- (UIImage *)imageByCropping:(UIImage *)imageToCrop toRect:(CGRect)rect
  {
      CGImageRef imageRef = CGImageCreateWithImageInRect([imageToCrop CGImage], rect);
  
      UIImage *croppedImage = [UIImage imageWithCGImage:imageRef];
      CGImageRelease(imageRef);
  
      return croppedImage;
  }
  </code></pre>
  
  <p>I called it like this</p>
  
  <pre><code>CGRect rect = CGRectMake(10, 72, 300, 300);
  
  UIImage *realImage = [self imageByCropping:[self.capturedImages objectAtIndex:0] toRect:rect];
  </code></pre>
  
  <p>What I get is a bad quality image with the wrong orientation. </p>
  
  <p>::EDIT::</p>
  
  <p>With Nitin's answer I can crop the correct part of the screen but the problem is it crops the view that follows the camera view, 'the confirmation view'. I suspect this is because Nitin's code uses</p>
  
  <p><code>UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();</code></p>
  
  <p>and because the ViewController in which all this is happening because the View Controller for the Confirmation View is the Controller in which this code is being executed. I will try to explain this with a small map</p>
  
  <p>CameraOverlay.xib(it uses this xib to create an overlay) &lt;===== CameraOverlayViewController ---------> ConfirmationView</p>
  
  <p>So when first the ViewController is evoked(button on Tab bar), it opens the camera(UIImagePickerController) with an overlay over it. Then once user clicks an image, the image is shown on the ConfirmationView. </p>
  
  <p>What I think is happening is when 
  <code>UIGraphicsBeginImageContextWithOptions(self.view.frame.size, YES, 1.0);</code>
  <code>[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];</code>
  <code>UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext();</code>
   these lines are being executed, the View at that time is ConfirmationView. </p>
  
  <p>Note: I call the function in</p>
  
  <p><code>(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info</code> method.</p>