React Native扫描二维码
采用:VisionCamera Documentation | VisionCamera (react-native-vision-camera.com) (opens new window)
# 安卓环境
安装
yarn add react-native-vision-camera
1更新清单
在
AndroidManifest.xml
文件中添加<uses-permission android:name="android.permission.CAMERA" />
1获取/请求权限
useEffect(() => { (async () => { const status = await Camera.requestCameraPermission(); setHasPermission(status === "authorized"); })(); }, []);
1
2
3
4
5
6使用MLKit Vision QRCODE扫描读取条形码的插件
安装
yarn add vision-camera-code-scanner
1安装
yarn add react-native-reanimated
1将插件添加到
react-native-reanimated/plugin
您的babel.config.js
module.exports = { plugins: [ ... 'react-native-reanimated/plugin', ], };
1
2
3
4
5
6注意
react-native-reanimated/plugin
必须列在最后插入作为您的
index.tsx
第一行import 'react-native-reanimated'
1添加到
babel.config.js
plugins: [ ... { globals: ['__scanCodes'], }, ],
1
2
3
4
5
6
使用
视图 import * as React from "react"; import { StyleSheet, Text } from "react-native"; import { useCameraDevices, useFrameProcessor } from "react-native-vision-camera"; import { Camera } from "react-native-vision-camera"; import { useScanBarcodes, BarcodeFormat, Barcode, scanBarcodes } from "vision-camera-code-scanner"; import { useEffect, useState } from "react"; import { runOnJS, useSharedValue } from "react-native-reanimated"; export default function CameraScreen() { const [hasPermission, setHasPermission] = React.useState(false); const devices = useCameraDevices(); const device = devices.back; const [barcodes, setBarcodes] = useState<Barcode[]>([]); // const [frameProcessor, barcodes] = useScanBarcodes([BarcodeFormat.QR_CODE], { // checkInverted: true // }); // Alternatively you can use the underlying function: const frameProcessor = useFrameProcessor((frame) => { "worklet"; const detectedBarcodes = scanBarcodes(frame, [BarcodeFormat.QR_CODE], { checkInverted: true }); runOnJS(setBarcodes)(detectedBarcodes); }, []); useEffect(() => { (async () => { const status = await Camera.requestCameraPermission(); setHasPermission(status === "authorized"); })(); }, []); return ( device != null && hasPermission && ( <> <Camera style={styles.camera} device={device} isActive={true} frameProcessor={frameProcessor} frameProcessorFps={5} /> {barcodes.map((barcode, idx) => ( <Text key={idx} style={styles.barcodeTextURL}> {barcode.displayValue} </Text> ))} </> ) ); } const styles = StyleSheet.create({ camera: { height: 460, width: "50%", alignSelf: "center" }, barcodeTextURL: { fontSize: 20, color: "white", fontWeight: "bold" } });
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# 报错解决方案
# 问题
在构建的时候报该错,Execution failed for task ':react-native-vision-camera:buildCMakeDebug[arm64-v8a]'.
# 解决方案
进入你的 android/build.gradle 并在 android/build.gradle 中为你所在的依赖项添加一个额外的类路径classpath 'com.android.tools.build:gradle:7.0.0'
上次更新: 2024/08/14, 04:14:33