当前位置:   article > 正文

react native 截图并保存到相册

react native 截图并保存到相册

首先需要三个包

  1. react-native-view-shot (截图,将图片保存到临时路径)
  2. react-native-fs (更改图片路径,从临时路径移出来)
  3. react-native-camera-roll/camera-roll (将图片保存到相册)

直接上代码

  1. import ViewShot from "react-native-view-shot";
  2. <ViewShot
  3. ref={viewShotRef}
  4. options={{ format: "jpg", quality: 0.9 }}
  5. >
  6. <View />
  7. </ViewShot>

这个是页面上,你要保存的截图使用ViewShot组件包括起来。

然后使用capture方法 获取截图的临时地址。

因为ios是不支持直接将临时图片保存到相册里的。

这里你还需要使用RNFS.moveFile将临时图片移动到一个持久目录下,然后再调用保存相册方法。

  1. const captureAndSaveScreenshot = async (viewShotRef: any) => {
  2. try {
  3. const uri = await viewShotRef.current.capture({
  4. format: 'jpg',
  5. quality: 0.9,
  6. result: 'tmpfile',
  7. snapshotContentContainer: true
  8. });
  9. const fileName = `screenshot_${Date.now()}.jpg`;
  10. const destPath = `${RNFS.DocumentDirectoryPath}/${fileName}`;
  11. console.log(destPath, 'destPath');
  12. await RNFS.moveFile(uri, destPath);
  13. const savedAsset = await CameraRoll.saveAsset(destPath);
  14. const photoUri = savedAsset.node.image.uri;
  15. return photoUri || destPath;
  16. } catch (error) {
  17. console.error('截图失败', error);
  18. throw error;
  19. }
  20. };

此处的photoUri是本地路径 ph:/ 开头的,destPath是一个持久路径。根据需要使用对应的路径地址

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/856140
推荐阅读
相关标签
  

闽ICP备14008679号