React Native中如何将View导出为图片数据

How to export View to image data in React Native

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

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

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

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

MyCoolView.m:

- (NSData *)export
{
  UIGraphicsBeginImageContext(self.bounds.size);
  [self.layer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return UIImagePNGRepresentation(image);
}
  1. 在本机视图管理器中公开 export 方法:

关键是传入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 方法:

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方法:

组件如下所示:

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

在某些函数中:

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