user2261079
user2261079

Reputation: 1

fast screenshot renderInContext: drawViewHierarchyInRect:afterScreenUpdates:

 (UIImage *)screenshot_1
{

    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);   
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];   
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;   
}

(UIImage *)screenshot_2
{

    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, 0);    
    [self.view drawViewHierarchyInRect:self.view.bounds afterScreenUpdates:YES];    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;  
}

then both in ios 7.0:

CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
UIImage *image = [self screenshot_1];
CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();
NSLog(@"cost : %f ms", (end - start) * 1000);

and then print : cost : 10.128021 ms

CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();   
UIImage *image = [self screenshot_2];  
CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();  
NSLog(@"cost : %f ms", (end - start) * 1000);  

and then print : cost : 68.924010 ms

my question is which is fast?

Upvotes: 0

Views: 860

Answers (1)

Fernando Mazzon
Fernando Mazzon

Reputation: 3591

Well since 10ms < 68ms the first one is obviously faster Beware however, the first method will not apply some transformations your view might have, while the second will. If you plan on using these functionality a lot, you should find a way to reuse a shared backing context.

Upvotes: 1

Related Questions