基于react-native-camera限定区域扫描

前言

目前,有很多扫描的轮子,今天来说说react-native-camera库的扫描应用

集成

集成方式传送门,这次不说这部分内容. 主要说说怎么限定区域扫描. (如果有同学在这部分遇到问题可以留言互相交流)

限定区域

react-native-camera库并没有暴露出限定区域范围的属性,所以需要我们去修改源代码,
iOS中,利用原生扫描机制AVCaptureMetadataOutput来实现扫描识别功能,
首先找到RNCamera类

《基于react-native-camera限定区域扫描》 1.png

然后修改限制区域方法:

       [[NSNotificationCenter defaultCenter] addObserverForName:AVCaptureInputPortFormatDescriptionDidChangeNotification
                                                          object:nil
                                                           queue:nil
                                                      usingBlock: ^(NSNotification *_Nonnull note) {
                                                          dispatch_async(self.sessionQueue, ^{
                                                              self.metadataOutput.rectOfInterest = CGRectMake(0.25, 0.25, 0.5, 0.5);
                                                          });

                                                      }];

即可完成修改扫描位置在屏幕中心.

坑点1

rectOfInterest参数顺序为(x, y, h, w), 且都是按比例分配

坑点2

必须在AVCaptureInputPortFormatDescriptionDidChangeNotification通知中回调, 设置区域才有效

坑点3

设置metadataOutput的rectOfInterest时, 需要添加线程异步处理, 请测不然RN上页面会有几秒钟卡顿

RN代码中写法

        <RNCamera
          style={{ flex: 1 }}
          ref={ref => {
            this.camera = ref;
          }}
          type={RNCamera.Constants.Type.back}
          barCodeTypes={[RNCamera.Constants.BarCodeType.qr]}
          flashMode={RNCamera.Constants.FlashMode.auto}
          onBarCodeRead={() => {
            // method
          }}
        />

如果需要添加扫描框与扫描线,代码如下
利用Animated动画实现即可, 关键代码如下, 需要在componentDidMount下启动动画, 且训话调用即可

<Animated.View
              style={[
                {
                  width,
                  backgroundColor: '#00ff00',
                  height: 2,
                },
                { transform: [{ translateY: this.state.move }] },
              ]}
            />

android限制扫描区域

文件所在位置:

《基于react-native-camera限定区域扫描》 1.png

实现居中扫描效果:

private BinaryBitmap generateBitmapFromImageData(byte[] imageData, int width, int height) {
    int scW = width / 2;
    int left =(width - scW) / 2;
    int top =(height - scW) / 2;
    PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(
        imageData, // byte[] yuvData
        width, // int dataWidth
        height, // int dataHeight
            left, // int left
            top, // int top
            scW, // int width
            scW, // int height
        false // boolean reverseHorizontal
    );
    return new BinaryBitmap(new HybridBinarizer(source));
  }
    原文作者:一天清晨
    原文地址: https://www.jianshu.com/p/021d65bec1dc
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞