Skip to content

Instantly share code, notes, and snippets.

@christopherdro
Created October 14, 2015 23:48
Show Gist options
  • Save christopherdro/67da4ab09e9810e4bf5b to your computer and use it in GitHub Desktop.
Save christopherdro/67da4ab09e9810e4bf5b to your computer and use it in GitHub Desktop.
#import "ViewSnapshotter.h"
#import "RCTConvert.h"
#import "RCTBridge.h"
#import "RCTUIManager.h"
@implementation ViewSnapshotter
RCT_EXPORT_MODULE()
@synthesize bridge = _bridge;
- (dispatch_queue_t)methodQueue
{
return dispatch_get_main_queue();
}
RCT_EXPORT_METHOD(saveSnapshotToPath:(nonnull NSNumber *)reactTag
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
UIView *view = [self.bridge.uiManager viewForReactTag:reactTag];
// defaults: snapshot the same size as the view, with alpha transparency, with current device's scale factor
UIGraphicsBeginImageContextWithOptions(view.frame.size, NO, 0.0);
[view drawViewHierarchyInRect:CGRectMake(0, 0, view.frame.size.width, view.frame.size.height) afterScreenUpdates:YES];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *data = UIImagePNGRepresentation(image);
NSError *error;
NSString *fileName = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *filePath = [NSString stringWithFormat:@"%@%@.png", NSTemporaryDirectory(), fileName];
BOOL writeSucceeded = [data writeToFile:filePath options:0 error:&error];
if (!writeSucceeded) {
reject(@[[NSString stringWithFormat:@"Could not write file at path %@", filePath]]);
}
resolve(filePath);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment