Skip to content

Instantly share code, notes, and snippets.

@acalism
Created June 29, 2016 10:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acalism/9b7b94c04fd73c503396b040ab29967f to your computer and use it in GitHub Desktop.
Save acalism/9b7b94c04fd73c503396b040ab29967f to your computer and use it in GitHub Desktop.
Snapshot any view for iOS
// Might be you will need to snapshot a particular view into an image. Previously we do like this:
// #import <QuartzCore/QuartzCore.h>
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *copied = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//On iOS 7 there's an updated API that is much faster:
UIGraphicsBeginImageContextWithOptions(view.bounds.size, NO, 0);
[view drawViewHierarchyInRect:view.bounds afterScreenUpdates:YES];
UIImage *copied = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//How efficient is the faster API? It is about 1.8x faster on iPhone 5. Time elapsed was down from 90ms to 50ms.
//If you want to create a view already drawn with the image, we can use an even more handy API:
UIView *newView = [view snapshotViewAfterScreenUpdates:YES];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment