首先需要三个包
- react-native-view-shot (截图,将图片保存到临时路径)
- react-native-fs (更改图片路径,从临时路径移出来)
- react-native-camera-roll/camera-roll (将图片保存到相册)
直接上代码
            
            
              javascript
              
              
            
          
          import ViewShot from "react-native-view-shot";
 
<ViewShot
    ref={viewShotRef}
    options={{ format: "jpg", quality: 0.9 }}
  >
    <View />
</ViewShot>这个是页面上,你要保存的截图使用ViewShot组件包括起来。
然后使用capture方法 获取截图的临时地址。
因为ios是不支持直接将临时图片保存到相册里的。
这里你还需要使用RNFS.moveFile将临时图片移动到一个持久目录下,然后再调用保存相册方法。
            
            
              javascript
              
              
            
          
           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是一个持久路径。根据需要使用对应的路径地址