Search code examples
objective-ciosscreenshotlayermask

ios: Screenshot doesn't display mask Layer


I have a view with a certain background color. I am masking this view with the following code:

UIView *colorableView = [[UIView* alloc] init];
colorableView.backgroundColor = someColor;

CALayer *maskLayer = [CALayer layer];
maskLayer.contents = (id)[UIImage imageNamed:maskImageName].CGImage;

colorableView.layer.mask = maskLayer;

Ok everything works fine there. The view gets masked, so some parts are transparent. Now I make a screenshot of this view:

CGRect frame = colorableView.frame;

UIGraphicsBeginImageContext(frame.size);

CGContextRef c = UIGraphicsGetCurrentContext();
CGContextTranslateCTM(someUninterestingCodeToGetACorrectPosition);

[self.view.layer renderInContext:c];
UIImage *screenShotImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return screenShotImage;

Taking a screenshot works (actually I display some other stuff above the view too and that gets displayed in the screenshot as well), but somehow, the mask is not recognized. Meaning what I get is a screenshot of a fully colored view (a rectangle) without the mask hiding some parts of it.

I guess ´UIGraphicsGetImageFromCurrentImageContext()`doesn't work with mask layers, so what can I do about it? I need to have a UIImage to display the screenshot in a mail.

Thanks a lot in advance


Solution

  • One way to fix this can be to use Quartz functions to clip the view (CGContextClip, I don't remember exactly, you'll have to dig a little bit into the documentation). Hope this will help