3

I'm trying to track down a bug in some iOS code for an iPad app. In one of our views, we've added sublayers to have a shadow and make sure the bottom of the view has rounded edges. Here's the code where we add the sublayers:

    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds
                                                   byRoundingCorners:(UIRectCornerBottomLeft|UIRectCornerBottomRight)
                                                         cornerRadii:CGSizeMake(12.0f, 12.0f)];

    // Create the shadow layer
    shadowLayer = [CAShapeLayer layer];
    [shadowLayer setFrame:self.bounds];
    [shadowLayer setMasksToBounds:NO];
    [shadowLayer setShadowPath:maskPath.CGPath];
    shadowLayer.shadowColor = [UIColor blackColor].CGColor;
    shadowLayer.shadowOffset = CGSizeMake(0.0f, 0.0f);
    shadowLayer.shadowOpacity = 0.5f;
    shadowLayer.shadowRadius = 6.0f;

    roundedLayer = [CALayer layer];
    [roundedLayer setFrame:self.bounds];
    [roundedLayer setBackgroundColor:[UIColor colorFromHex:@"#e4ecef"].CGColor];

    [self.layer insertSublayer:shadowLayer atIndex:0];

    // Add inner view (since we're rounding corners, parent view can't mask to bounds b/c of shadow - need extra view)
    maskLayer = [CAShapeLayer layer];
    maskLayer.frame = self.bounds;
    maskLayer.path = maskPath.CGPath;
    innerView = [[UIView alloc] initWithFrame:self.bounds];
    innerView.backgroundColor = [UIColor whiteColor];
    innerView.layer.mask = maskLayer;
    [self addSubview:innerView];

It shows up fine on the screen of the iPad, but I want to take a screenshot programmatically. I've added a category to UIView with this method:

- (UIImage*)screenshot {
    UIGraphicsBeginImageContext(self.frame.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
    return viewImage;
}

When I look at the screenshot that is taken, it no longer has the rounded corners or the shadow behind my view. Why aren't they showing up?

hoonsan
  • 116
  • 6

2 Answers2

2

Found an explanation here: CALayer renderInContext

Additionally, layers that use 3D transforms are not rendered, nor are layers that specify backgroundFilters, filters, compositingFilter, or a mask values.

It looks like some sublayers can't be handled by renderInContext, which is why they aren't showing up in my screenshots.

Community
  • 1
  • 1
hoonsan
  • 116
  • 6
0

Gradient sublayers

The snapshot is not taking any gradient layers with alpha channel in it. Remove the alpha from colors, works for me

Saranjith
  • 11,242
  • 5
  • 69
  • 122