如何将视图导出到React Native中的图像数据

时间:2015-08-06 12:19:07

标签: react-native

我正在尝试在React Native中导出View的渲染图形。例如,我的观点是:

<View> <Image/> // Some image <Rectangle /> // Some little <Circle /> // Some circle </View>

如何将容器View中呈现的图形提取为任何图像数据格式?

1 个答案:

答案 0 :(得分:5)

请参阅https://stackoverflow.com/a/31936516/528842

  1. 子类RCTView并添加export方法:
  2. MyCoolView.m

    - (NSData *)export
    {
      UIGraphicsBeginImageContext(self.bounds.size);
      [self.layer renderInContext:UIGraphicsGetCurrentContext()];
      UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
      UIGraphicsEndImageContext();
      return UIImagePNGRepresentation(image);
    }
    
    1. 在本机视图管理器中公开export方法:
    2. 关键是传入reactTag,它是对本机组件的引用。

      MyCoolViewManager.m

      RCT_EXPORT_METHOD(export:(NSNumber *)reactTag callback:(RCTResponseSenderBlock)callback) {
        [self.bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, RCTSparseArray *viewRegistry) {
          MyCoolView *view = viewRegistry[reactTag];
          if (![view isKindOfClass:[MyCoolView class]]) {
            RCTLogMustFix(@"Invalid view returned from registry, expecting MyCoolView, got: %@", view);
          }
          NSData * imageData = [view export];
          callback(@[[NSNull null], [imageData base64EncodedStringWithOptions:0]]);
        }];
      }
      
      1. 从React组件公开export方法:
      2. MyCoolView.js

        var React = require('react-native');
        var NativeModules = require('NativeModules');
        var MyCoolViewManager = NativeModules.MyCoolViewManager;
        var findNodeHandle = require('findNodeHandle');
        
        class MyCoolView extends React.Component{
            // ...
            export() {
                return new Promise((resolve, reject) => {
                    MyCoolViewManager.export(
                        findNodeHandle(this),
                        (error, result) => {
                            if (error) {
                                reject(error);
                            } else {
                                resolve(result);
                                // now we've got the base64 encoded data of the exported image
                            }
                        }
                    );
                });
            }
        }
        
        1. 调用export方法:
        2. 组件如下所示:

          <MyCoolView ref='myCoolView'>
              <Image />
                  <Rectangle />
                  <Circle />
              </View>
          </MyCoolView>
          

          在某些功能中:

          this.refs.myCoolView.export()
              .then(base64data => {
                  console.log(base64data);
              }, error => {
                  console.error(error);
              });