title: Cropping UIImage to custom path and keeping correct resolution?
body: <p><a href="https://i.stack.imgur.com/ujdKx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ujdKx.jpg" alt="enter image description here"></a></p>
  
  <p>I have a view (blue background...) which I'll call "main" here, on main I added a <code>UIImageView</code> that I then rotate, pan and scale. On main I have a another subview that shows the cropping area. Anything out of that under the darker area needs to be cropped.</p>
  
  <p>I am trying to figure out how to properly create a cropped image from this state. I want the resulting image to look like this:</p>
  
  <p><a href="https://i.stack.imgur.com/SHQWO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SHQWO.png" alt="enter image description here"></a></p>
  
  <p>I want to make sure to keep the resolution of the image.</p>
  
  <p>Any idea?</p>
  
  <p>I have tried to figure out how to use the layer.mask property of the UIImageView. After some feedback, I think I could have another view (B) on the blue view, on B I would then add the image view, so then I would make sure that B's frame would match the rect of the cropping mask overlay. I think that could work? The only thing is I want to make sure I don't lose resolution.</p>
  
  <p>So, earlier I tried this:</p>
  
  <pre><code>maskShape.frame = imageView.bounds
  maskShape.path = UIBezierPath(rect: CGRect(x: 20, y: 20, width: 200, height: 200)).cgPath
  imageView.layer.mask = maskShape
  </code></pre>
  
  <p>The rect was just a test rect and the image would be cropped to that path, but, I wasn't sure how to get a UIImage from all this that could keep the large resolution of the original image</p>
  
  <p>So, I have implemented the method suggested by marco, it all works with the exception of keeping the resolution.</p>
  
  <p>I use this call to take a screenshot of the view the contains the image and I have it clip to bounds:</p>
  
  <pre><code>public func renderToImage(afterScreenUpdates: Bool = false) -&gt; UIImage {
      let rendererFormat = UIGraphicsImageRendererFormat.default()
      rendererFormat.opaque = isOpaque
      let renderer = UIGraphicsImageRenderer(size: bounds.size, format: rendererFormat)
  
      let snapshotImage = renderer.image { _ in
          drawHierarchy(in: bounds, afterScreenUpdates: afterScreenUpdates)
      }
      return snapshotImage
  }
  </code></pre>
  
  <p>The image I get is correct, but is not as sharp as the one I crop.</p>
  
  <p>Hoe can I keep the resolution high?</p>