基於react-native-camera限定區域掃描
前言
目前,有很多掃描的輪子,今天來說說react-native-camera庫的掃描應用
整合
整合方式 ofollow,noindex">傳送門 ,這次不說這部分內容. 主要說說怎麼限定區域掃描. (如果有同學在這部分遇到問題可以留言互相交流)
限定區域
react-native-camera庫並沒有暴露出限定區域範圍的屬性,所以需要我們去修改原始碼,
iOS中,利用原生掃描機制AVCaptureMetadataOutput來實現掃描識別功能,
首先找到RNCamera類

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 }] }, ]} />