模板版本:v0.4.0
react-native-camera
本项目基于 react-native-camera 开发。
请到三方库的 Releases 发布地址查看配套的版本信息:@react-native-ohos/react-native-camera Releases。对于未发布到npm的旧版本,请参考安装指南安装tgz包。
| 三方库名称 | 三方库版本 | 发布信息 | 支持RN版本 | Autolink | 编译API版本 | 社区基线版本 | npm地址 |
|---|---|---|---|---|---|---|---|
| @react-native-ohos/react-native-camera | ~3.42.0 (开发中) | @react-native-ohos/react-native-camera Releases | 0.82 | 是 | API12+ | v3.40.0 | Npm Address |
| @react-native-ohos/react-native-camera | ~3.41.1 | @react-native-ohos/react-native-camera Releases | 0.72/0.77 | 否 | API12+ | v3.40.0 | Npm Address |
1. 安装与使用
进入到工程目录并输入以下命令:
npm
npm install @react-native-ohos/react-native-camera
yarn
yarn add @react-native-ohos/react-native-camera
下面的代码展示了这个库的基本使用场景:
使用时 import 的库名不变。
import * as React from 'react';
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { RNCamera } from "@react-native-ohos/react-native-camera";
export function CameraExample() {
const cameraRef = React.useRef<RNCamera>(null);
const takePicture = () => {
const camera = cameraRef.current;
if (!camera) {
return;
}
camera
.takePictureAsync({ quality: 0.5 })
.then((photoResult: any) => {
console.log('takepicture result:' + (photoResult?.path ?? photoResult?.uri));
})
.catch((error: unknown) => {
console.warn('takepicture failed:', error);
});
};
return (
<View style={styles.container}>
<RNCamera
ref={cameraRef}
type="back"
autoFocus="on"
flashMode="off"
videoStabilizationMode="off"
style={styles.cameraPreview}
/>
<TouchableOpacity style={styles.actionBtn} onPress={takePicture}>
<Text style={styles.actionBtnText}>拍照</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1 },
cameraPreview: { width: '100%', aspectRatio: 56 / 100 },
actionBtn: {
margin: 10,
padding: 10,
backgroundColor: '#1E90FF',
borderRadius: 8,
alignItems: 'center',
},
actionBtnText: { color: '#fff', fontSize: 16 },
});
export default {
title: 'Camera',
description: '使用 react-native-camera 拍照',
examples: [
{
name: 'CameraExample',
title: 'Camera Preview',
description: '点击按钮调用相机拍照',
render(): React.ReactNode {
return <CameraExample />;
},
},
],
};
2. Link
| 是否支持autolink | RN框架版本 | |
|---|---|---|
| ~3.42.0 | 是 | 0.82 |
| ~3.41.1 | 否 | 0.72/0.77 |
使用AutoLink的工程需要根据该文档配置,Autolink框架指导文档:https://gitcode.com/openharmony-sig/ohos_react_native/blob/master/docs/zh-cn/Autolinking.md
如您使用的版本支持 Autolink,并且工程已接入 Autolink,可跳过ManualLink配置。
ManualLink: 此步骤为手动配置原生依赖项的指导
首先需要使用 DevEco Studio 打开项目里的 HarmonyOS 工程 harmony。
2.1 Overrides RN SDK
为了让工程依赖同一个版本的 RN SDK,需要在工程根目录的 oh-package.json5 添加 overrides 字段,指向工程需要使用的 RN SDK 版本。替换的版本既可以是一个具体的版本号,也可以是一个模糊版本,还可以是本地存在的 HAR 包或源码目录。
关于该字段的作用请阅读官方说明:
{
"overrides": {
"@rnoh/react-native-openharmony": "^0.72.38" // ohpm 在线版本
// "@rnoh/react-native-openharmony" : "./react_native_openharmony.har" // 指向本地 har 包的路径
// "@rnoh/react-native-openharmony" : "./react_native_openharmony" // 指向源码路径
}
}
2.2 引入原生端代码
目前有两种方法:
- 通过 har 包引入(在 IDE 完善相关功能后该方法会被遗弃,目前首选此方法);
- 直接链接源码。
方法一:通过 har 包引入(推荐)
har 包位于三方库安装路径的 `harmony` 文件夹下。
打开 entry/oh-package.json5,添加以下依赖
"dependencies": {
"@react-native-ohos/react-native-camera": "file:../../node_modules/@react-native-ohos/react-native-camera/harmony/reactNativeCamera.har"
}
点击右上角的 sync 按钮
或者在终端执行:
cd entry
ohpm install
方法二:直接链接源码
如需使用直接链接源码,请参考[直接链接源码说明](./link-source-code.md)
2.3 配置 CMakeLists 和引入 NativeCameraPackage
打开 entry/src/main/cpp/CMakeLists.txt,添加:
+ set(OH_MODULES "${CMAKE_CURRENT_SOURCE_DIR}/../../../oh_modules")
# RNOH_BEGIN: manual_package_linking_1
+ add_subdirectory("${OH_MODULES}/@react-native-ohos/react-native-camera/src/main/cpp" ./reactNativeCamera)
# RNOH_END: manual_package_linking_1
# RNOH_BEGIN: manual_package_linking_2
+ target_link_libraries(rnoh_app PUBLIC rnoh_native_camera)
# RNOH_END: manual_package_linking_2
打开 entry/src/main/cpp/PackageProvider.cpp,添加:
#include "RNOH/PackageProvider.h"
#include "generated/RNOHGeneratedPackage.h"
+ #include "NativeCameraPackage.h"
using namespace rnoh;
std::vector<std::shared_ptr<Package>> PackageProvider::getPackages(Package::Context ctx) {
return {
std::make_shared<RNOHGeneratedPackage>(ctx),
+ std::make_shared<NativeCameraPackage>(ctx)
};
}
2.4 在 ArkTs 侧引入 react-native-camera 组件
找到 function buildCustomRNComponent(),一般位于 entry/src/main/ets/pages/index.ets 或 entry/src/main/ets/rn/LoadBundle.ets,添加:
...
+ import { ReactCameraView } from '@react-native-ohos/react-native-camera';
@Builder
export function buildCustomRNComponent(ctx: ComponentBuilderContext) {
...
+ if (ctx.componentName === ReactCameraView.NAME) {
+ ReactCameraView({
+ ctx: ctx.rnComponentContext,
+ tag: ctx.tag,
+ })
+ }
...
}
...
本库使用了混合方案,需要添加组件名。
在entry/src/main/ets/pages/index.ets 或 entry/src/main/ets/rn/LoadBundle.ets 找到常量 arkTsComponentNames 在其数组里添加组件名
const arkTsComponentNames: Array<string> = [
SampleView.NAME,
GeneratedSampleView.NAME,
PropsDisplayer.NAME,
+ ReactCameraView.NAME
];
2.5 在 ArkTs 侧引入 ReactNativeCameraPackage
打开 entry/src/main/ets/RNPackagesFactory.ts,添加:
...
+ import { ReactNativeCameraPackage, FaceDectorPackage } from '@react-native-ohos/react-native-camera/ts';
export function createRNPackages(ctx: RNPackageContext): RNPackage[] {
return [
new SamplePackage(ctx),
+ new ReactNativeCameraPackage(ctx),
+ new FaceDectorPackage(ctx)
];
}
2.6 运行
点击右上角的 sync 按钮
或者在终端执行:
cd entry
ohpm install
然后编译、运行即可。
3. 约束与限制
3.1 兼容性
要使用此库,需要使用正确的 React-Native 和 RNOH 版本。另外,还需要使用配套的 DevEco Studio 和 手机 ROM。
在以下版本验证通过:
- RNOH: 0.72.98; SDK: HarmonyOS-5.0.0(API12); IDE: DevEco Studio 5.0.3.906; ROM: NEXT.0.0.71;
- RNOH: 0.77.18; SDK: HarmonyOS 6.0.0.47 (API Version 20); IDE: DevEco Studio 6.0.0.858; ROM: 6.0.0.107;
- RNOH: 0.82.22; SDK: HarmonyOS 6.0.0 Release SDK; IDE: DevEco Studio 6.0.0.878; ROM: 6.0.0.130;
3.2 编译运行API要求
当前三方库所有版本均已实现版本隔离,支持在 `API12+` 工程编译,及 `API12+` ROM运行。
以下功能依赖特定版本的API,使用 `低于指定API版本的工程编译` 或 `低于指定API版本的ROM运行` 均可能导致部分功能受限。
whiteBalance属性需要在支持API20+的工程编译,并在支持API20+的 ROM 上运行,方可生效。
3.3 权限要求
在 entry 目录下的module.json5中添加权限
打开 entry/src/main/module.json5,添加:
...
"requestPermissions": [
+ {
+ "name": "ohos.permission.CAMERA",
+ "reason": "$string:camera_reason",
+ "usedScene": {
+ "abilities": [
+ "EntryAbility"
+ ],
+ "when":"inuse"
+ }
+ },
+ {
+ "name": "ohos.permission.MICROPHONE",
+ "reason": "$string:microphone_reason",
+ "usedScene": {
+ "abilities": [
+ "EntryAbility"
+ ],
+ "when":"inuse"
+ }
+ },
]
在 entry 目录下添加申请以上权限的原因
打开 entry/src/main/resources/base/element/string.json,添加:
...
{
"string": [
+ {
+ "name": "camera_reason",
+ "value": "使用相机"
+ },
+ {
+ "name": "microphone_reason",
+ "value": "使用麦克风"
+ },
]
}
4. 属性
"Platform"列表示该属性在原三方库上支持的平台。
"HarmonyOS Support"列为 yes 表示 HarmonyOS 平台支持该属性;no 则表示不支持;partially 表示部分支持。使用方法跨平台一致,效果对标 iOS 或 Android 的效果。
RNCamera
| Name | Description | Type | Required | Platform | HarmonyOS Support |
|---|---|---|---|---|---|
| children | 设置子组件 | View | no | iOS/Android | yes |
| type | 选择摄像头 | string | no | iOS/Android | yes |
| flashMode | 设置闪光灯 | string | no | iOS/Android | yes |
| exposure | 设置曝光 | number | no | iOS/Android | yes |
| autoFocus | 设置自动对焦 | string | no | iOS/Android | yes |
| whiteBalance | 白平衡 | string | no | iOS/Android | yes |
| captureAudio | 是否开启录音 | boolean | no | iOS/Android | yes |
| zoom | 设置缩放比例 | number | no | iOS/Android | yes |
| focusDepth | 非自动对焦时,设置对焦值 | number | no | iOS/Android | yes |
| maxZoom | 设置最大缩放比例 | number | no | iOS/Android | yes |
| pictureSize | 设置默认图片分辨率 | string | no | iOS/Android | yes |
| notAuthorizedView | 未授权显示的ui | View | no | Android | no |
| pendingAuthorizationView | 正在授权显示的ui | View | no | Android | no |
| ratio | 相机比例 | string | no | Android | no |
| defaultVideoQuality | 默认视频分辨率 | string | no | iOS/Android | yes |
camera
| Name | Description | Type | Required | Platform | HarmonyOS Support |
|---|---|---|---|---|---|
| onBarCodeRead | 接收barcode扫描数据 | BarCodeReadEvent | no | iOS/Android | yes |
| onFacesDetected | 接收人脸识别数据 | Face | no | iOS/Android | no |
| takePictureAsync | 照相 | TakePictureResponse | no | iOS/Android | yes |
| recordAsync | 开始录像 | RecordResponse | no | iOS/Android | yes |
| stopRecording | 停止录像 | void | no | iOS/Android | yes |
| getCameraIdAsync | 获取可用摄像头id列表 | CameraType | no | iOS/Android | yes |
| refreshAuthorization | 请求权限 | void | no | iOS/Android | yes |
5. 遗留问题
6. 其他
- notAuthorizedView属性,pendingAuthorizationView属性是android独有的属性,申请授权时显示的UI,harmony已经提供授权时的弹窗。
- ratio是android独有的属性,在ios无效果 源库readme位置
7. 开源协议
本项目基于 MIT License (MIT) ,请自由地享受和参与开源。