Search code examples
uiimageviewuiimagemaskuibezierpathcashapelayer

How to save a masked image in iOS


This is what I am doing to mask an image.. This is working fine.. My problem is that self.imgView.image is not the masked image.. How can I retrieve masked images? Thanks.

- (void) setClippingPath:(UIBezierPath *)clippingPath : (UIImageView *)imgView {

    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.frame = self.imgView.frame;
    maskLayer.path = [clippingPath CGPath];
    maskLayer.fillColor = [[UIColor whiteColor] CGColor];
    maskLayer.backgroundColor = [[UIColor clearColor] CGColor];

    self.imgView.layer.mask = maskLayer;

}

Solution

  • You can use this method to covert a CALayer to a UIImage. It's from https://stackoverflow.com/a/3454613/749786

    - (UIImage *)imageFromLayer:(CALayer *)layer
    {
      UIGraphicsBeginImageContext([layer frame].size);
    
      [layer renderInContext:UIGraphicsGetCurrentContext()];
      UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    
      UIGraphicsEndImageContext();
    
      return outputImage;
    }