سؤال

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;

}
هل كانت مفيدة؟

المحلول

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;
}

نصائح أخرى

Here's how in Swift 5.4.

func image(from layer: CALayer?) -> UIImage? {
    UIGraphicsBeginImageContext(layer?.frame.size ?? CGSize.zero)

    if let context = UIGraphicsGetCurrentContext() {
        layer?.render(in: context)
    }
    let outputImage = UIGraphicsGetImageFromCurrentImageContext()

    UIGraphicsEndImageContext()

    return outputImage
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top