Search code examples
ioscropcore-imagecashapelayer

How to convert CAShapeLayer coordinates to CIRectangleFeature for manual crop


I am dealing with manual image crop functionality. For this am drawing CAShapeLayer with four coordinates called topLeft, topRight, bottomRight and bottomLeft. User can pan the points and select the crop area. I am stuck at converting these points to Core image coordinates and further cropping with CIPerspectiveTransform.


Solution

  • Set image to imageView And masking imageView with shape layer.

    self.imageView = img
    imageView.layer.mask = shapeLayer // set here your shape layer
    

    Now your imageView have crop image.

    Get image from current context as follow

    UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, 0);
    imageView.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // check cropping image
    let resultImageView = UIImageView(frame: self.view.frame)
    resultImageView.image = image
    self.view.addSubview(resultImageView)