3

I am trying to create an image of a UIView with CALayer sublayers. With this code

- (UIImage*)snapshot{
    UIGraphicsBeginImageContext(self.bounds.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;
}

I get an image, but it doesn't accurately represent what is displayed on the screen. In particular, it does not respect the CAShapeLayer mask property. My rounded corners don't appear in the image.

Here is a comparison of how an example appears on the screen to how it appears in the image: enter image description here

Just to clarify, the image on the right is placed in the same position as the old object, basically rasterizing the object. That is why there is the same background; it is not part of the object that I'm capturing the image of.

How can I capture an image of the object while retaining the CAShapeLayer mask in the image?

EDIT: It seems it was the layer mask that was the problem, not the path.

Meet Doshi
  • 4,241
  • 10
  • 40
  • 81
jadengeller
  • 1,307
  • 1
  • 14
  • 26

2 Answers2

1

Instead of using self.bounds.size and self.layer, just use that view whose corner is rounded. suppose if it is imageView then

- (UIImage*)snapshot
{
    UIGraphicsBeginImageContext(imageview.size);
    [imageview.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return viewImage;
}
Meet Doshi
  • 4,241
  • 10
  • 40
  • 81
Stan Roger
  • 67
  • 12
  • The view contains many subclassed UIButtons as subviews. These UIButton subclass objects contain multiple CAShapelayers as sublayers. It is these CAShapeLayers that contain the rounded corners. How could I do this without capturing each and every CALayer as a separate image? – jadengeller Jun 15 '12 at 06:49
  • This really doesn't answer the question. – jadengeller Jun 15 '12 at 16:39
1

Straight from the CALayer Class reference:

Additionally, layers that ... specify backgroundFilters, filters, compositingFilter, or a mask values ... are not rendered.

I'm using a mask, not a CGPath. (Well, a CALayer with a path is my mask, but still.)

Another problem, however, is I cannot switch to using a path instead of a mask, because I am using gradients and CAGradientLayer does not have a path property like CAShapeLayer, which is why I used a mask.

jadengeller
  • 1,307
  • 1
  • 14
  • 26