How to export image data in React Native

I am trying to export a rendered drawing View

to React Native. For example, my view is like:

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

How do I extract the rendered image from the container View

to any image data format?

+3


source to share


1 answer


see fooobar.com/questions/384359 / ...

  • Subclass RCTView

    and add a method export

    :

MyCoolView.m

:

- (NSData *)export
{
  UIGraphicsBeginImageContext(self.bounds.size);
  [self.layer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return UIImagePNGRepresentation(image);
}

      

  1. 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]]);
  }];
}

      



  1. 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
                    }
                }
            );
        });
    }
}

      

  1. 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







All Articles