react native 截图并生存到相册

打印 上一主题 下一主题

主题 990|帖子 990|积分 2970

首先需要三个包

  • react-native-view-shot (截图,将图片生存到临时路径)
  • react-native-fs (更改图片路径,从临时路径移出来)
  • 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是一个恒久路径。根据需要使用对应的路径地点

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

玛卡巴卡的卡巴卡玛

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表