title: crop UIImage to the shape of a rectangular overlay - Swift
body: <p>I am pretty new to Swift.
  I intend to draw a rectangle and capture the image in the rectangular overlay.
  <a href="https://i.stack.imgur.com/ZwlEB.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZwlEB.jpg" alt="enter image description here"></a></p>
  
  <p>I drew a transparent image over the camera.               </p>
  
  <pre><code>            let imagePicker = UIImagePickerController()
              imagePicker.delegate = self
              imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
              imagePicker.mediaTypes = [kUTTypeImage as String]
              imagePicker.allowsEditing = true
  
  
              var overlayedImageView: UIImageView = UIImageView(image: UIImage(named: "transparent.png"))
              var cgRect: CGRect = CGRect(x: 200, y: 50, width: 100, height: 400)
              overlayedImageView.frame = cgRect
              imagePicker.cameraOverlayView = overlayedImageView
  
              self.presentViewController(imagePicker, animated: true,
                  completion: nil)
  </code></pre>
  
  <p>This is what i do after i capture the image</p>
  
  <pre><code>    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
  
  
      let mediaType = info[UIImagePickerControllerMediaType] as! String
  
      self.dismissViewControllerAnimated(true, completion: nil)
  
      if mediaType == (kUTTypeImage as String) {
          let image = info[UIImagePickerControllerOriginalImage]
              as! UIImage
  
          imageView.image = cropToBoundsNew(image)
  
          if (newMedia == true) {
              UIImageWriteToSavedPhotosAlbum(image, self,
                  "image:didFinishSavingWithError:contextInfo:", nil)
          } else if mediaType == (kUTTypeMovie as String) {
              // Code to support video here
          }
  
      }
  }
  </code></pre>
  
  <p><strong>My Problem is  the <em>quality of the image diminishes</em></strong> </p>
  
  <pre><code>    func cropToBoundsNew(image: UIImage) -&gt; UIImage {
      let contextImage: UIImage = UIImage(CGImage: image.CGImage!)
      let contextSize: CGSize = contextImage.size
  
      let rect: CGRect = CGRectMake(200, 50, 100, 400)
  
      let imageRef: CGImageRef = CGImageCreateWithImageInRect(contextImage.CGImage, rect)!
  
      let image: UIImage = UIImage(CGImage: imageRef, scale: image.scale, orientation: image.imageOrientation)
  
      return image
  }
  </code></pre>