您的位置:首页 > 汽车 > 时评 > react native 截图并保存到相册

react native 截图并保存到相册

2024/9/8 12:24:13 来源:https://blog.csdn.net/weixin_52063276/article/details/140525070  浏览:    关键词:react native 截图并保存到相册

首先需要三个包

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

直接上代码

import ViewShot from "react-native-view-shot";<ViewShotref={viewShotRef}options={{ format: "jpg", quality: 0.9 }}><View />
</ViewShot>

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

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

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

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

 const captureAndSaveScreenshot = async (viewShotRef: any) => {try {const uri = await viewShotRef.current.capture({format: 'jpg',quality: 0.9,result: 'tmpfile',snapshotContentContainer: true});const fileName = `screenshot_${Date.now()}.jpg`;const destPath = `${RNFS.DocumentDirectoryPath}/${fileName}`;console.log(destPath, 'destPath');await RNFS.moveFile(uri, destPath);const savedAsset = await CameraRoll.saveAsset(destPath);const photoUri = savedAsset.node.image.uri;return photoUri || destPath;} catch (error) {console.error('截图失败', error);throw error;}};

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com