bobbypage
bobbypage

Reputation: 2169

How to capture the contents of a UIView and change it into a UIImage?

I currently have a view and I would like to change it into a UIImage. I would like to do this because the UIImage class is much better for what I need to do. How would you capture the contents of a UIView and copy the contents into a UIImage?

Thanks,

-David

Upvotes: 5

Views: 2566

Answers (3)

Shafraz Buhary
Shafraz Buhary

Reputation: 663

Add Following method to UIView category and use

- (UIImage*) capture {
    UIGraphicsBeginImageContext(self.bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [self.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

Upvotes: 0

v01d
v01d

Reputation: 1566

Like this:

UIGraphicsBeginImageContext(myView.bounds.size);
[myView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *myImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

You will need to include the CoreGraphics framework, and import the CALayer.h:

#import <QuartzCore/CALayer.h>

Upvotes: 7

Raphael Caixeta
Raphael Caixeta

Reputation: 7846

Here, try this

CGImageRef screen = UIGetScreenImage();
UIImage *screenImage = [UIImage imageWithCGImage:screen];

That will take a screenshot of the screen, so in theory capturing all of the view's elements and gives you a UIImage to work off of. Hope that helps!

Upvotes: 2

Related Questions