react native 截图并保存到相册

首先需要三个包

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

相关推荐
_pengliang12 分钟前
react native ios 2个modal第二个不显示
javascript·react native·react.js
纳兰瑞雪13 分钟前
nodeJs electron程式开发demo
开发语言·前端·javascript
爱上妖精的尾巴37 分钟前
7-8 WPS JS宏 对象使用实例5--按多字段做多种汇总
javascript·后端·restful·wps·jsa
我算哪枝小绿植40 分钟前
react实现日历拖拽效果
前端·react.js·前端框架
白粥44 分钟前
【HTML】文本格式化
前端·javascript·html
只有干货1 小时前
动态表单组件渲染并采集 展示vue component
javascript·vue.js·ecmascript
mario_z1 小时前
基于kmines类聚线段算法
前端·javascript·算法
干前端1 小时前
基于PDF.js的安全PDF预览组件实现:从虚拟滚动到水印渲染
javascript·安全·pdf
OEC小胖胖1 小时前
04|从 Lane 位图到 `getNextLanes`:React 更新优先级与纠缠(Entangle)模型
前端·react.js·前端框架
愤怒的可乐1 小时前
从零构建大模型智能体:ReAct 智能体实战
前端·react.js·前端框架