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是一个持久路径。根据需要使用对应的路径地址

相关推荐
CC_Amber8 分钟前
Flexbox 在 RN 中的行为差异 & css注意
react native
CQU_JIAKE10 分钟前
4.4【Q】
java·前端·javascript
GISer_Jing24 分钟前
Electron 全场景调试实战指南
javascript·electron·状态模式
We་ct26 分钟前
JS手撕:性能优化、渲染技巧与定时器实现
开发语言·前端·javascript·面试·性能优化·定时器·性能
taWSw5OjU35 分钟前
vue对接海康摄像头-H5player
开发语言·前端·javascript
huwuhang1 小时前
跨平台电子书阅读器 | Readest最新版 安卓版+PC版全平台
android·前端·javascript
Shirley~~1 小时前
力扣hot100:每日温度
开发语言·javascript·ecmascript
条tiao条1 小时前
不止语法糖:TypeScript Set 与 Map 深度解析
前端·javascript·typescript
freewlt1 小时前
React Server Components 深度解析:从原理到实战的完整指南
前端·javascript·react.js
zhensherlock1 小时前
Protocol Launcher 系列:1Writer iOS 上的 Markdown 文档管理
javascript·笔记·ios·typescript·node.js·iphone·ipad