How to export image data in React Native
1 answer
see fooobar.com/questions/384359 / ...
- Subclass
RCTView
and add a methodexport
:
MyCoolView.m
:
- (NSData *)export
{
UIGraphicsBeginImageContext(self.bounds.size);
[self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return UIImagePNGRepresentation(image);
}
- Extract the method
export
in your native view manager:
The key is to pass in reactTag
, which is a reference to the native component.
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]]);
}];
}
- Output method
export
from React component:
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
}
}
);
});
}
}
- Call the method
export
:
The component looks like this:
<MyCoolView ref='myCoolView'>
<Image />
<Rectangle />
<Circle />
</View>
</MyCoolView>
In some function:
this.refs.myCoolView.export()
.then(base64data => {
console.log(base64data);
}, error => {
console.error(error);
});
+5
source to share