title: Clipping a UIImage to a custom UIBezierPath while preserving the image quality
body: <p>I'm having a problem when it comes to clipping a photo to a custom UIBezierPath. Instead of displaying the area within the path, as it should, it displays another part of the photo instead (of different size and position than where it should be, but still the same shape as was drawn). Note I'd also like to keep the full quality of the original photo.</p>
  
  <p>I've included photos and captions below to explain my problem in more depth. If anyone could give me another way to do such a thing I'll gladly start over.</p>
  
  <p><img src="https://i.stack.imgur.com/dv7eL.png" alt="The user draws a UIBezierPath with his finger">
  Above is an illustration of the UIImage within a UIImageView, all within a UIView of which the CAShapeLayer that displays the UIBezierPath is a sublayer. For this example assume that the path in red was drawn by the user.</p>
  
  <p><img src="https://i.stack.imgur.com/hLtAc.png" alt="Visualization">
  In this diagram is the CAShapeLayer and a graphics context created with the original image's size. How would I clip the context so that the result below is produced (please excuse the messiness of it)?</p>
  
  <p><img src="https://i.stack.imgur.com/k0BQM.png" alt="The result">
  This is the result I'd like to be produced when all is said and done. Note I'd like it to still be the same size/quality as the original.</p>
  
  <p>Here are some relevant portions of my code:</p>
  
  <p>This clips an image to a path</p>
  
  <pre><code>-(UIImage *)maskImageToPath:(UIBezierPath *)path {
      // Precondition: the path exists and is closed
      assert(path != nil);
  
  
      // Mask the image, keeping original size
      UIGraphicsBeginImageContextWithOptions(self.size, NO, 0);
  
      [path addClip];
      [self drawAtPoint:CGPointZero];
  
      // Extract the image
      UIImage *maskedImage = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
  
      return maskedImage;
  }
  </code></pre>
  
  <p>This adds points to the UIBezierPath</p>
  
  <pre><code> - (void)drawClippingLine:(UIPanGestureRecognizer *)sender {
      CGPoint nextPoint = [sender locationInView:self];
  
      // If UIBezierPath *clippingPath is nil, initialize it.
      // Otherwise, add another point to it.
      if(!clippingPath) {
          clippingPath = [UIBezierPath bezierPath];
          [clippingPath moveToPoint:nextPoint];
      }
      else {
          [clippingPath addLineToPoint:nextPoint];
      }
  
      UIGraphicsBeginImageContext(_image.size);
      [clippingPath stroke];
      UIGraphicsEndImageContext();
  
  
  }
  </code></pre>