Sergey Mikhanov
Sergey Mikhanov

Reputation: 8960

iPhone: UIImage obtained after rendering a view is solid black

I'm using this method to render a UIView into a UIImage:

+ (UIImage *)imageWithView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return image;
}

The resulting image is of the right size (as shown by the UIImage's size property), but its contents is solid black colour. The view passed there definitely contains some graphics, but it's not rendered. Any idea why?

Upvotes: 1

Views: 320

Answers (1)

Daniel G. Wilson
Daniel G. Wilson

Reputation: 15055

This is the code I use to capture images of a UIView:

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
else
    UIGraphicsBeginImageContext(self.view.bounds.size);

CGContextRef context = UIGraphicsGetCurrentContext();

[view.layer renderInContext:context];

UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return img;

Your code looks fine to me. You can try swapping mine out to see if it helps, but I'd cite it to be a separate issue from the code you posted.

Upvotes: 1

Related Questions