Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to take screenShot of UIView

I've searched a lot but only found two methods to take screen shot of UIView. first renderInContext: I've used it in a way

CGContextRef context = [self createBitmapContextOfSize:CGSizeMake(nImageWidth, nImageHeight)];
CGAffineTransform flipVertical = CGAffineTransformMake(1, 0, 0, -1, 0, nImageHeight);
CGContextConcatCTM(context, flipVertical);
[self.layer setBackgroundColor:[UIColor clearColor].CGColor];
[self.layer renderInContext:context];
CGImageRef cgImage = CGBitmapContextCreateImage(context);
UIImage* background = [UIImage imageWithCGImage: cgImage];
CGImageRelease(cgImage);

Second drawViewHierarchyInRect: which I've used as

UIImage *background = nil;

UIGraphicsBeginImageContextWithOptions (self.bounds.size, NO, self.window.screen.scale);

if ([self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)])
{
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];   
}
background = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

I know that the second one is faster than first and it work for me for iPhone because the view has low size. but when I capturing from iPad the video become jerky. Can Any body tell me faster way of taking screen shot. any help would be highly appreciated

like image 433
AltafBangash Avatar asked Sep 03 '25 13:09

AltafBangash


2 Answers

Regarding performance, the Apple Docs state the following:

In addition to -drawViewHierarchyInRect:afterScreenUpdates:, UIView now provides another two snapshot related methods, -snapshotViewAfterScreenUpdates: and -resizableSnapshotViewFromRect:afterScreenUpdates:withCapInsets:. UIScreen also has -snapshotViewAfterScreenUpdates:.

Unlike UIView's -drawViewHierarchyInRect:afterScreenUpdates:, these methods return a UIView object. If you are looking for a new snapshot view, use one of these methods. It will be more efficient than calling -drawViewHierarchyInRect:afterScreenUpdates: to render the view contents into a bitmap image yourself. You can use the returned view as a visual stand-in for the current view/screen in your app. For example, you might use a snapshot view for animations where updating a large view hierarchy might be expensive.

like image 84
Daniel Galasko Avatar answered Sep 05 '25 05:09

Daniel Galasko


There is a third method for taking a snapshot that is much much quicker than either of these but it returns a UIView.

- (UIView *)snapshotViewAfterScreenUpdates:(BOOL)afterUpdates

If you are just using the snapshot to place as a background "image" etc... then I'd use this instead.

However, this is only available for iOS8.

To use it just do...

UIView *snapshotView = [someView snapshotViewAfterScreenUpdates:YES];
like image 30
Fogmeister Avatar answered Sep 05 '25 05:09

Fogmeister