iOS 原生扫描二维码 ----扫描有效区域的问题

这几天在写RN插件的时候发现一很奇葩的问题,就是封装原生扫描二维码、条码的插件,其中的问题是,在二维码还没有进入扫描框的时候扫描结果就出来了,这样给用户的体验相当的不好。于是乎,我就去网上找各种资料看看大家有没有解决过类似的问题。

这里有为仁兄似乎已经解决了这个问题http://www.2cto.com/kf/201411/356046.html里面解决上面的这个问题方法是可以有效的处理问题,但还是有些问题,而且这个方法是我无法理解为什么要那样子去设置rectOfInterest的,大家可以试试便知。

下面我就介绍一种可以有效解决问题的方法,在AVCaptureMetadataOutput类里面的rectOfInterest属性注释里面写着下面一段英文

/*! @propertyrectOfInterest @abstract    Specifies a rectangleofinterestforlimitingthesearch areaforvisual metadata. @discussion    The valueofthispropertyisa CGRectthatdeterminesthereceiver's rectangleofinterestforeach frameofvideo. The rectangle's originistop leftandisrelativetothecoordinatespaceofthedevice providingthemetadata. Specifying a rectOfInterest may improve detection performanceforcertain typesofmetadata. The default valueofthispropertyisthevalue CGRectMake(0,0,1,1). Metadata objectswhosebounds donotintersectwiththerectOfInterest willnotbe returned. */


扫码时 previewLayer 的扫描范围是整个可视范围的,但有些需求可能需要指定扫描的区域,虽然我觉得这样很没有必要,因为整个屏幕都可以扫又何必指定到某个框呢?但如果真的需要这么做可以设定 metadataOutput 的 rectOfInterest。

1)rectOfInterest 的值比较特别,需要进行转化。它的默认值是 (0.0, 0.0, 1.0, 1.0)。

metadataOutput.rectOfInterest=[previewLayer metadataOutputRectOfInterestForRect:CGRectMake(80, 80, 160, 160)]; // 假设扫码框的 Rect 是 (80, 80, 160, 160)


2) rectOfInterest 不可以直接在设置 metadataOutput 时接着设置,而需要在这个 AVCaptureInputPortFormatDescriptionDidChangeNotification 通知里设置,否则 metadataOutputRectOfInterestForRect: 转换方法会返回 (0, 0, 0, 0)。

[[NSNotificationCenterdefaultCenter] addObserverForName:AVCaptureInputPortFormatDescriptionDidChangeNotification                                                        object:nilqueue:[NSOperationQueue currentQueue]                                                    usingBlock: ^(NSNotification*_Nonnull note) {      metadataOutput.rectOfInterest= [previewLayer metadataOutputRectOfInterestForRect:CGRectMake(80,80,160,160)];}];


当如此设置完rectOfInterest之后问题就有效的解决了,希望这个能帮助到同在此坑跌倒的同志们。

你可能感兴趣的:(iOS 原生扫描二维码 ----扫描有效区域的问题)