RNViewShot.m 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. #import "RNViewShot.h"
  2. #import <AVFoundation/AVFoundation.h>
  3. #import <React/RCTLog.h>
  4. #import <React/UIView+React.h>
  5. #import <React/RCTUtils.h>
  6. #import <React/RCTConvert.h>
  7. #import <React/RCTScrollView.h>
  8. #import <React/RCTUIManager.h>
  9. #import <React/RCTBridge.h>
  10. @implementation RNViewShot
  11. RCT_EXPORT_MODULE()
  12. @synthesize bridge = _bridge;
  13. - (dispatch_queue_t)methodQueue
  14. {
  15. return RCTGetUIManagerQueue();
  16. }
  17. RCT_EXPORT_METHOD(captureScreen: (NSDictionary *)options
  18. resolve:(RCTPromiseResolveBlock)resolve
  19. reject:(RCTPromiseRejectBlock)reject)
  20. {
  21. [self captureRef: [NSNumber numberWithInt:-1] withOptions:options resolve:resolve reject:reject];
  22. }
  23. RCT_EXPORT_METHOD(releaseCapture:(nonnull NSString *)uri)
  24. {
  25. NSString *directory = [NSTemporaryDirectory() stringByAppendingPathComponent:@"ReactNative"];
  26. // Ensure it's a valid file in the tmp directory
  27. if ([uri hasPrefix:directory] && ![uri isEqualToString:directory]) {
  28. NSFileManager *fileManager = [NSFileManager new];
  29. if ([fileManager fileExistsAtPath:uri]) {
  30. [fileManager removeItemAtPath:uri error:NULL];
  31. }
  32. }
  33. }
  34. RCT_EXPORT_METHOD(captureRef:(nonnull NSNumber *)target
  35. withOptions:(NSDictionary *)options
  36. resolve:(RCTPromiseResolveBlock)resolve
  37. reject:(RCTPromiseRejectBlock)reject)
  38. {
  39. [self.bridge.uiManager addUIBlock:^(__unused RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
  40. // Get view
  41. UIView *view;
  42. if ([target intValue] == -1) {
  43. UIWindow *window = [[UIApplication sharedApplication] keyWindow];
  44. view = window.rootViewController.view;
  45. } else {
  46. view = viewRegistry[target];
  47. }
  48. if (!view) {
  49. reject(RCTErrorUnspecified, [NSString stringWithFormat:@"No view found with reactTag: %@", target], nil);
  50. return;
  51. }
  52. // Get options
  53. CGSize size = [RCTConvert CGSize:options];
  54. NSString *format = [RCTConvert NSString:options[@"format"]];
  55. NSString *result = [RCTConvert NSString:options[@"result"]];
  56. BOOL snapshotContentContainer = [RCTConvert BOOL:options[@"snapshotContentContainer"]];
  57. // Capture image
  58. BOOL success;
  59. UIView* rendered;
  60. UIScrollView* scrollView;
  61. if (snapshotContentContainer) {
  62. if (![view isKindOfClass:[RCTScrollView class]]) {
  63. reject(RCTErrorUnspecified, [NSString stringWithFormat:@"snapshotContentContainer can only be used on a RCTScrollView. instead got: %@", view], nil);
  64. return;
  65. }
  66. RCTScrollView* rctScrollView = view;
  67. scrollView = rctScrollView.scrollView;
  68. rendered = scrollView;
  69. }
  70. else {
  71. rendered = view;
  72. }
  73. if (size.width < 0.1 || size.height < 0.1) {
  74. size = snapshotContentContainer ? scrollView.contentSize : view.bounds.size;
  75. }
  76. if (size.width < 0.1 || size.height < 0.1) {
  77. reject(RCTErrorUnspecified, [NSString stringWithFormat:@"The content size must not be zero or negative. Got: (%g, %g)", size.width, size.height], nil);
  78. return;
  79. }
  80. CGPoint savedContentOffset;
  81. CGRect savedFrame;
  82. if (snapshotContentContainer) {
  83. // Save scroll & frame and set it temporarily to the full content size
  84. savedContentOffset = scrollView.contentOffset;
  85. savedFrame = scrollView.frame;
  86. scrollView.contentOffset = CGPointZero;
  87. scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
  88. }
  89. UIGraphicsBeginImageContextWithOptions(size, NO, 0);
  90. success = [rendered drawViewHierarchyInRect:(CGRect){CGPointZero, size} afterScreenUpdates:YES];
  91. UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  92. UIGraphicsEndImageContext();
  93. if (snapshotContentContainer) {
  94. // Restore scroll & frame
  95. scrollView.contentOffset = savedContentOffset;
  96. scrollView.frame = savedFrame;
  97. }
  98. if (!success) {
  99. reject(RCTErrorUnspecified, @"The view cannot be captured. drawViewHierarchyInRect was not successful. This is a potential technical or security limitation.", nil);
  100. return;
  101. }
  102. if (!image) {
  103. reject(RCTErrorUnspecified, @"Failed to capture view snapshot. UIGraphicsGetImageFromCurrentImageContext() returned nil!", nil);
  104. return;
  105. }
  106. // Convert image to data (on a background thread)
  107. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  108. NSData *data;
  109. if ([format isEqualToString:@"jpg"]) {
  110. CGFloat quality = [RCTConvert CGFloat:options[@"quality"]];
  111. data = UIImageJPEGRepresentation(image, quality);
  112. }
  113. else {
  114. data = UIImagePNGRepresentation(image);
  115. }
  116. NSError *error = nil;
  117. NSString *res = nil;
  118. if ([result isEqualToString:@"base64"]) {
  119. // Return as a base64 raw string
  120. res = [data base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];
  121. }
  122. else if ([result isEqualToString:@"data-uri"]) {
  123. // Return as a base64 data uri string
  124. NSString *base64 = [data base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];
  125. res = [NSString stringWithFormat:@"data:image/%@;base64,%@", format, base64];
  126. }
  127. else {
  128. // Save to a temp file
  129. NSString *path = RCTTempFilePath(format, &error);
  130. if (path && !error) {
  131. if ([data writeToFile:path options:(NSDataWritingOptions)0 error:&error]) {
  132. res = path;
  133. }
  134. }
  135. }
  136. if (res && !error) {
  137. resolve(res);
  138. return;
  139. }
  140. // If we reached here, something went wrong
  141. if (error) reject(RCTErrorUnspecified, error.localizedDescription, error);
  142. else reject(RCTErrorUnspecified, @"viewshot unknown error", nil);
  143. });
  144. }];
  145. }
  146. @end