react native踩坑日记(1):react-native中集成二维码扫描,识别相册二维码

声明:写这篇文章的时候安卓手机未测试,苹果手机可正常使用,如果有后续结果,会在更新,但是理论上是适配ios和安卓
首先选择如下三个npm

import {RNCamera} from 'react-native-camera';
import ImagePicker from 'react-native-image-picker';
import {QRreader} from 'react-native-qr-scanner';

安装方法

yarn add react-native-camera
yarn add react-native-image-picker

其中重点说明一下,识别选择相册中的二维码,在百度的过程中有一个npm包出现的次数最多eact-native-local-barcode-recognizer,这个有人使用,你也可以试试。但是我安装的时候出现了点问题报错如下:
在这里插入图片描述
无奈解决不掉这个问题,就换成了react-native-qr-scanner,请使用以下两种方式安装,详细地址

yarn add git+https://github.com/ihor-linovitsky/react-native-qr-scanner.git
or 
npm install git+https://github.com/ihor-linovitsky/react-native-qr-scanner.git

具体使用方法可点击详细地址查看。

还遗留一个问题,大佬能够解决的话麻烦在评论里回复一下:

  1. 写了个扫描动画,想要实现扫描成功动画就停止。

上面两个正常安装即可,react-native-camerareact-native-image-picker,使用方法去github或者npm官网查阅,附上我的代码。扫描成功的后的结果都会通过alert弹出,没做任何处理,方便自己做其他操作

提示:安装完插件记得 cd ios -> pod install,可能有的不需要,虽然0.6以后不需要手动link,但是还是需要运行,以防万一,RN的报错贼难处理

import React, {Component} from 'react';
import {
  Dimensions,
  StyleSheet,
  View,
  Animated,
  Easing,
  Text,
  Button,
  Alert,
} from 'react-native';
import {RNCamera} from 'react-native-camera';
import ImagePicker from 'react-native-image-picker';
import {QRreader} from 'react-native-qr-scanner';
import {Modal, Provider} from '@ant-design/react-native';

const options = {
  title: '请选择',
  quality: 0.8,
  cancelButtonTitle: '取消',
  takePhotoButtonTitle: null,
  chooseFromLibraryButtonTitle: '选择相册',
  customButtons: [{name: 'hangge', title: '输入编码'}],
  allowsEditing: true,
  noData: false,
  storageOptions: {
    skipBackup: true,
    path: 'images',
  },
};

export default class App extends Component {
  static navigationOptions = ({navigation}) => {
    return {
      title: '扫一扫',
      headerRight: () => (
        <View style={styles.rightBtn}>
          <Button
            title={
              navigation.state.params.torchState === 'off' ? '开灯' : '关灯'
            }
            onPress={() => navigation.state.params.onchangeTorchState()}
          />
          <Button
            title="+"
            onPress={() => navigation.state.params.choosePicker()}
          />
        </View>
      ),
    };
  };

  //构造函数
  constructor(props) {
    super(props);
    this.state = {
      torchState: 'off',
      qrCode: null,
    };
    this.moveAnim = new Animated.Value(0);
  }

  componentDidMount() {
    this.startAnimation();
    this.props.navigation.setParams({
      choosePicker: this.choosePicker,
      onchangeTorchState: this.onchangeTorchState,
      torchState: this.state.torchState,
    });
  }

  _onBarCodeRead = (value) => {
    const {qrCode} = this.state;
    if (qrCode) {
      return;
    }
    this.setState(
      {
        qrCode: value,
      },
      () => {
        alert(this.state.qrCode.data);   // 打印出扫描后的数据
      },
    );
  };

  // 扫描动画
  startAnimation = () => {
    this.moveAnim.setValue(0);
    Animated.timing(this.moveAnim, {
      toValue: 1,
      duration: 1500,
      easing: Easing.linear,
      useNativeDriver: true,
    }).start(() => this.startAnimation());
  };

  // 修改torchState 状态
  onchangeTorchState = () => {
    const {torchState} = this.state;
    this.setState(
      {
        torchState: torchState === 'off' ? 'ON' : 'off',
      },
      () => {
        this.props.navigation.setParams({torchState: this.state.torchState});
      },
    );
  };

// 从相册获取二维码并扫描返回结果
  choosePicker = () => {
    ImagePicker.showImagePicker(options, (response) => {
      console.log('Response = ', response);
      if (response.didCancel) {
        console.log('User cancelled image picker');
      } else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      } else if (response.customButton) {
        this.onClickModal();
      } else {
        if (response.uri) {
          var path = response.path;
          if (!path) {
            path = response.uri;
          }
          QRreader(path)
            .then((data) => {
              Alert.alert(data);
            })
            .catch((err) => {
              Alert.alert('识别失败');
            });
        }
      }
    });
  };

  onClickModal = () => {
    Modal.prompt(
      '请输入编码',
      null,
      (code) => console.log(`code: ${code}`),
      'code-password',
      null,
      ['请输入编码'],
    );
  };

  //渲染
  render() {
    const winWidth = Dimensions.get('window').width;
    const winHeight = Dimensions.get('window').height;
    return (
      <Provider>
        <View style={styles.container}>
          <RNCamera
            style={styles.preview}
            ratio={'16:9'}
            defaultVideoQuality={RNCamera.Constants.VideoQuality['720p']}
            scanAreaLimit={true}
            scanAreaX={(115 * winWidth) / 750}
            scanAreaY={(328 * winHeight) / 1334}
            scanAreaWidth={(522 * winWidth) / 750}
            scanAreaHeight={(521 * winHeight) / 1334}
            flashMode={
              this.state.torchState == 'off'
                ? RNCamera.Constants.FlashMode.off
                : RNCamera.Constants.FlashMode.torch
            }
            onBarCodeRead={this._onBarCodeRead.bind(this)}>
            <View style={styles.rectangleContainer}>
              <View style={styles.rectangle} />
              <Animated.View
                style={[
                  styles.border,
                  {
                    transform: [
                      {
                        translateY: this.moveAnim.interpolate({
                          inputRange: [0, 1],
                          outputRange: [-200, 0],
                        }),
                      },
                    ],
                  },
                ]}
              />
              <Text style={styles.rectangleText}>
                将二维码放入框内,即可自动扫描
              </Text>
            </View>
          </RNCamera>
        </View>
      </Provider>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'column',
  },
  preview: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  btnText: {color: 'white', fontSize: 16},
  rectangleContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
  },
  rectangle: {
    height: 200,
    width: 200,
    borderWidth: 1,
    borderColor: '#00FF00',
    backgroundColor: 'transparent',
  },
  rectangleText: {
    flex: 0,
    color: '#fff',
    marginTop: 10,
  },
  border: {
    flex: 0,
    width: 200,
    height: 2,
    backgroundColor: '#00FF00',
  },
  rightBtn: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'flex-end',
  },
});

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

琞、小菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值