首先需要三个包
- react-native-view-shot (截图,将图片生存到临时路径)
- react-native-fs (更改图片路径,从临时路径移出来)
- react-native-camera-roll/camera-roll (将图片生存到相册)
直接上代码
- import ViewShot from "react-native-view-shot";
-
- <ViewShot
- ref={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是一个恒久路径。根据需要使用对应的路径地点
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |