Andrew
Andrew

Reputation: 16051

Create an image of part of the screen?

I have a series of sublayers that are created on part of the screen in my app and would like for it to take this and save it as an image, then show the image instead to hopefully make the app run a little faster. How can i get an image saved (temporarily, so not accessible in the photos app) of those layers? They're all inside a UIView if that helps.

Upvotes: 0

Views: 360

Answers (3)

vikingosegundo
vikingosegundo

Reputation: 52227

I created this category:

.h

#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>

@interface UIView (ViewCapture)
    - (UIImage*)captureView;
@end

.m

#import "UIView+ViewCapture.h"

@implementation UIView (ViewCapture)

- (UIImage*)captureView
{    
    CGRect rect = self.frame;  
    UIGraphicsBeginImageContext(rect.size);  
    CGContextRef context = UIGraphicsGetCurrentContext();  
    [self.layer renderInContext:context];  
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();  
    UIGraphicsEndImageContext();  
    return img;    
}
@end

Use it like this:

UIImage *screenshot = [aView captureView];

Save and Load UIImage in Documents directory on iPhone

Upvotes: 1

klefevre
klefevre

Reputation: 8735

You could what you want with a screenshot :

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

Upvotes: 1

Travis Jensen
Travis Jensen

Reputation: 5420

Use UIGraphicsBeginImageContext and the related functions, like below (to create an image of a button):

UIGraphicsBeginImageContext(button.frame.size);
CGContextRef theContext = UIGraphicsGetCurrentContext();
[button.layer renderInContext:theContext];
UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
NSData *theData = UIImagePNGRepresentation(theImage);
UIGraphicsEndImageContext();    

For a working example (that will actually save the image in the simulator), see https://github.com/dermdaly/ButtonMaker.

Upvotes: 0

Related Questions