rntpc_react-native-view-shot:

分支23Tags5
文件最后提交记录最后更新时间
17 天前
21 天前
16 天前
1 个月前
6 年前
16 天前
16 天前
3 年前
24 天前
16 天前
9 年前
1 个月前
1 个月前
8 天前
8 天前
1 个月前
16 天前
9 年前
16 天前

文档模板:v0.4.2

react-native-view-shot

本项目基于 react-native-view-shot 开发。

该第三方库的仓库已迁移至 Gitcode,且支持直接从 npm 下载,新的包名为:@react-native-ohos/react-native-view-shot。 版本所属关系如下:

三方库名称 三方库版本(npm地址) 发布信息 支持RN版本 Autolink 编译API版本 社区基线版本 源码地址
@react-native-ohos/react-native-view-shot ~4.0.0 Gitcode Releases 0.84.* / 0.82.* API12+ 5.1.1 master
@react-native-ohos/react-native-view-shot ~3.9.0 Gitcode Releases 0.77.* API12+ 3.8.0 br_rnoh0.77
@react-native-ohos/react-native-view-shot ~3.8.1 Gitcode Releases 0.72.* API12+ 3.8.0 br_rnoh0.72
@react-native-oh-tpl/react-native-view-shot <=3.8.0-0.3.2@deprecated Github Releases(deprecated) 0.72.* API12+ 3.8.0 sig

简介

一个将React Native视图捕获到图像的库。

下载安装

进入到工程目录并输入以下命令:

npm

npm install @react-native-ohos/react-native-view-shot

yarn

yarn add @react-native-ohos/react-native-view-shot
是否支持autolink RN框架版本
~4.0.0 0.84.* / 0.82.*

使用AutoLink的工程需要根据该文档配置,Autolink框架指导文档:https://gitcode.com/CPF-RN/ohos_react_native/blob/master/docs/zh-cn/Autolinking.md

如您使用的版本支持 Autolink,并且工程已接入 Autolink,可跳过ManualLink配置。

ManualLink: 此步骤为手动配置原生依赖项的指导

首先需要使用 DevEco Studio 打开项目里的 HarmonyOS 工程 harmony。

1.在工程根目录的 oh-package.json5 添加 overrides 字段

{
  ...
  "overrides": {
    "@rnoh/react-native-openharmony" : "./react_native_openharmony"
  }
}

引入原生端代码

目前有两种方法:

  1. 通过 har 包引入(在 IDE 完善相关功能后该方法会被遗弃,目前首选此方法);
  2. 直接链接源码。

方法一:通过 har 包引入(推荐)

har 包位于三方库安装路径的 `harmony` 文件夹下。

打开 entry/oh-package.json5,添加以下依赖

"dependencies": {
    "@rnoh/react-native-openharmony": "file:../react_native_openharmony",

    "@react-native-ohos/react-native-view-shot": "file:../../node_modules/@react-native-ohos/react-native-view-shot/harmony/view_shot.har"
  }

点击右上角的 sync 按钮

或者在终端执行:

cd entry
ohpm install

方法二:直接链接源码

如需使用直接链接源码,请参考[直接链接源码说明](https://gitcode.com/CPF-RN/usage-docs/blob/master/zh-cn/link-source-code.md)

配置 CMakeLists 和引入 ViewShotPackage

打开 entry/src/main/cpp/CMakeLists.txt,添加:

project(rnapp)
cmake_minimum_required(VERSION 3.4.1)
set(RNOH_APP_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
+ set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
set(RNOH_CPP_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../../../../../react-native-harmony/harmony/cpp")

add_subdirectory("${RNOH_CPP_DIR}" ./rn)

# RNOH_BEGIN: manual_package_linking_1
add_subdirectory("../../../../sample_package/src/main/cpp" ./sample-package)
+ add_subdirectory("${OH_MODULES}/@react-native-ohos/react-native-view-shot/src/main/cpp" ./view-shot)
# RNOH_BEGIN: manual_package_linking_1

add_library(rnoh_app SHARED
    "./PackageProvider.cpp"
    "${RNOH_CPP_DIR}/RNOHAppNapiBridge.cpp"
)

target_link_libraries(rnoh_app PUBLIC rnoh)

# RNOH_BEGIN: manual_package_linking_2
target_link_libraries(rnoh_app PUBLIC rnoh_sample_package)
+ target_link_libraries(rnoh_app PUBLIC rnoh_view_shot)
# RNOH_BEGIN: manual_package_linking_2

打开 entry/src/main/cpp/PackageProvider.cpp,添加:

#include "RNOH/PackageProvider.h"
#include "SamplePackage.h"
+ #include "ViewShotPackage.h"

using namespace rnoh;

std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx) {
    return {
      std::make_shared<SamplePackage>(ctx),
+     std::make_shared<ViewShotPackage>(ctx)
    };
}

在 ArkTs 侧引入 ViewShotPackage

打开 entry/src/main/ets/RNPackagesFactory.ts,添加:

  ...
+ import { ViewShotPackage } from '@react-native-ohos/react-native-view-shot/ts';

export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
  return [
    new SamplePackage(ctx),
+   new ViewShotPackage(ctx),
  ];
}

运行

点击右上角的 sync 按钮

或者在终端执行:

cd entry
ohpm install

然后编译、运行即可。

约束与限制

兼容性

本文档内容基于以下环境验证通过:

  1. RNOH: 0.84.1; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112;
  2. RNOH: 0.82.1; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.112;

使用示例

下面的代码展示了这个库的基本使用场景:

使用时 import 的库名不变。

import React from "react";
import { View, Text, Button } from "react-native";
import ViewShot, { captureRef, captureScreen } from "react-native-view-shot";

export function ViewShotDemo() {
  const view = React.useRef < View > (null);
  const ref = React.useRef(null);
  const onCapture = (res) => {
    console.info("onCapture callback");
  };
  const onCaptureFailure = (err) => {
    console.info("onCaptureFailure " + JSON.stringify(err));
  };

  return (
    <View>
      <View
        ref={view}
        collapsable={false}
        style={{ backgroundColor: "#ffffff" }}
      >
        <Text style={{ color: "#000", marginBottom: 30 }}>
          Hello OpenHarmony
        </Text>
        <Text style={{ color: "#000", marginBottom: 30 }}>Hello HarmonyOS</Text>
        <Text style={{ color: "#000", marginBottom: 30 }}>
          Hello HarmonyOS Next.
        </Text>

        <ViewShot
          ref={ref}
          style={{ backgroundColor: "#ffffff" }}
          onCapture={onCapture}
          onCaptureFailure={onCaptureFailure}
          captureMode="mount"
        >
          <Text style={{ color: "#000", marginBottom: 30 }}>Hello World</Text>
        </ViewShot>

      </View>
      <Button
        title="captureRef"
        onPress={() => {
          captureRef(view).then((res) => {
            console.info(`captureRef: ${JSON.stringify(res)}`);
          });
        }}
      />
      <Button
        title="ViewShot capture"
        onPress={() => {
          ref.current?.capture().then((res) => {
            console.info(`ViewShotRef.capture: ${res}`);
          });
        }}
      />
      <Button
        title="captureScreen"
        onPress={() => {
          captureScreen().then((res) => {
            console.info(`captureScreen success: ${res}`);
          });
        }}
      />
    </View>
  );
}

属性

"Platform"列表示该属性在原三方库上支持的平台。

"HarmonyOS Support"列为 yes 表示 HarmonyOS 平台支持该属性;no 则表示不支持;partially 表示部分支持。使用方法跨平台一致,效果对标 iOS 或 Android 的效果。

名称 参数类型 默认值 必填 平台 HarmonyOS平台支持 描述
captureMode "mount" | "continuous" | "update" undefined No Android, iOS Yes 未定义时(默认),截图不会自动进行,需要使用 ref 并手动调用 capture()
"mount":在组件挂载时自动截图一次。(需注意图片加载不会被等待,如需等待图片加载完成,建议使用 "none" 并在 Image#onLoad 后调用 viewShotRef.capture()。)
"continuous" 实验性功能,会持续不断地截图。仅适用于非常特殊的场景。
"update" 实验性功能,每次 React 重绘(on did update)时都会截图。仅适用于非常特殊的场景。
onCapture (uri: string) => void None No Android, iOS Yes 当定义了 captureMode 时,截图成功后会调用此回调函数,并传入截图结果。
onCaptureFailure (error: Error) => void None No Android, iOS Yes 当定义了 captureMode 时,截图失败时会调用此回调函数。
options CaptureOptions None No Android, iOS Partially 截图配置项。
children ReactNode None No Android, iOS Yes 实际需要被栅格化(截图)的内容。
onLayout (event: LayoutChangeEvent) => void None No Android, iOS Yes 组件挂载或布局变化时调用,并接收布局事件。
style StyleProp&lt;ViewStyle&gt; None No Android, iOS Yes 应用于 ViewShot 容器的视图样式。

options属性详情

名称 参数类型 默认值 必填 平台 HarmonyOS平台支持 描述
fileName string None No Android Yes 文件名,长度必须至少为 3 个字符。
width / height number None No Android, iOS Yes 最终图片的宽度和高度(会根据 View 的边界进行缩放。如果需要保持原始像素大小,请勿提供此参数)。
quality number 1 No Android, iOS Yes 图片质量,范围为 0.0 - 1.0(默认值)。(仅适用于有损压缩格式,如 jpg)
format "jpg" | "png" | "webp" | "webm" | "raw" "png" No Android, iOS Partially 图片格式,可选 png/jpg/webp/webm,默认为 png。鸿蒙平台不支持 raw 格式(仅 Android 支持)。
result "tmpfile" | "base64" | "data-uri" | "zip-base64" "tmpfile" No Android, iOS Partially 保存截图的方式,可选值如下:
"tmpfile"(默认):保存到临时文件(仅在应用运行期间有效)。
"base64":编码为 base64 并返回原始字符串。建议仅用于小图片,因为可能会导致卡顿(字符串会通过桥接传输)。注意:这不是 data uri,如需 data uri 请使用 data-uri。
"data-uri":与 base64 相同,但会包含 Data URI scheme 请求头。
"zip-base64":使用 Zip/Deflate 算法压缩数据,然后转换为 Base64 并返回原始字符串。注意:鸿蒙平台不支持 zip-base64(仅 Android 支持)。
snapshotContentContainer boolean false No Android, iOS No 如果为 true 且 view 为 ScrollView,则会使用 "content container" 的高度,而非容器本身的高度。
useRenderInContext boolean None No iOS No 修改 iOS 截图策略,使用 renderInContext 方法替代 drawViewHierarchyInRect,可能适用于某些特定场景。
handleGLSurfaceViewOnAndroid boolean false No Android No 当 handleGLSurfaceViewOnAndroid 设置为true且视图是 SurfaceView(或包含在视图树中)时,该视图的内容将会被捕获。

API

"Platform"列表示该属性在原三方库上支持的平台。

"HarmonyOS Support"列为 yes 表示 HarmonyOS 平台支持该属性;no 则表示不支持;partially 表示部分支持。使用方法跨平台一致,效果对标 iOS 或 Android 的效果。

名称 类型 参数类型 返回值 必填 平台 鸿蒙平台支持 描述
captureRef function view: CaptureTarget; optionsObject?: CaptureOptions Promise&lt;string&gt; view: yes; optionsObject: no Android, iOS yes 组件截图
captureScreen function optionsObject?: CaptureOptions Promise&lt;string&gt; no Android, iOS yes 屏幕截图
releaseCapture function uri: string void yes Android, iOS yes 资源释放
ViewShotRef.capture() function / Promise&lt;string&gt; / Android, iOS yes ViewShot 组件的命令式截图方法,通过 viewShotRef.current.capture() 调用,并使用组件 options 属性中的截图配置;未设置 captureMode 时可用它手动触发截图。

遗留问题

其他

目录结构

/rntpc_react-native-view-shot  # 项目根目录
│  LICENSE
│  OAT.xml
│  package.json
│  README.md
│  README.OpenSource
│  README_en.md
│
├─example
│
├─harmony
│  │  view_shot.har     # 编译后的 HAR 包(HarmonyOS Archive)
│  │
│  └─view_shot          # 鸿蒙适配核心代码
│      │  .gitignore
│      │  build-profile.json5
│      │  hvigorfile.ts
│      │  Index.ets
│      │  oh-package.json5
│      │  ts.ets
│      │
│      └─src
│          └─main
│            │  module.json5
│            │
│            ├─cpp                       # C++ 原生层(新架构 Fabric/TurboModule)
│            │      CMakeLists.txt
│            │      ViewShotPackage.h
│            │      ViewShotTurboModule.cpp
│            │      ViewShotTurboModule.h
│            │
│            ├─ets                      # ArkTS 业务层
│            │      Logger.ts
│            │      ViewShotPackage.ets
│            │      ViewShotTurboModule.ets
│            │
│            └─resources                # 资源文件
│
└─src                                  
    │  index.tsx
    │  RNViewShot.ts
    │  RNViewShot.web.ts
    │
    └─specs
            NativeRNViewShot.ts

贡献代码

使用过程中发现任何问题都可以提交 Issue,当然,也非常欢迎提交 PR

开源协议

本项目基于 The MIT License (MIT) ,请自由地享受和参与开源。