我正在尝试在React Native中导出View
的渲染图形。例如,我的观点是:
<View>
<Image/> // Some image
<Rectangle /> // Some little
<Circle /> // Some circle
</View>
如何将容器View
中呈现的图形提取为任何图像数据格式?
答案 0 :(得分:5)
请参阅https://stackoverflow.com/a/31936516/528842
RCTView
并添加export
方法: MyCoolView.m
:
- (NSData *)export
{
UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return UIImagePNGRepresentation(image);
}
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]]);
}];
}
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
}
}
);
});
}
}
export
方法:组件如下所示:
<MyCoolView ref='myCoolView'>
<Image />
<Rectangle />
<Circle />
</View>
</MyCoolView>
在某些功能中:
this.refs.myCoolView.export()
.then(base64data => {
console.log(base64data);
}, error => {
console.error(error);
});