gpt4 book ai didi

react-native - 如何在 React Native 中将 View 导出为图像数据

转载 作者:行者123 更新时间:2023-12-04 05:21:42 33 4
gpt4 key购买 nike

我正在尝试导出 View 的渲染图形在 React Native 中。例如,我的观点是这样的:
<View>
<Image/> // Some image
<Rectangle /> // Some little
<Circle /> // Some circle
</View>

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

最佳答案

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 native View 管理器中的方法:

  • 关键是传入 reactTag这是对 native 组件的引用。
    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来自 React 组件的方法:
  • 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);
    });

    关于react-native - 如何在 React Native 中将 View 导出为图像数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31855592/

    33 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com