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

这几天在写RN插件的时候发现一很奇葩的问题,就是封装原生扫描二维码、条码的插件,其中的问题是,在二维码还没有进入扫描框的时候扫描结果就出来了,这样给用户的体验相当的不好。于是乎,我就去网上找各种资料看看大家有没有解决过类似的问题。
这里有为仁兄似乎已经解决了这个问题http://www.2cto.com/kf/201411/356046.html里面解决上面的这个问题方法是可以有效的处理问题,但还是有些问题,而且这个方法是我无法理解为什么要那样子去设置rectOfInterest的,大家可以试试便知。
下面我就介绍一种可以有效解决问题的方法,在AVCaptureMetadataOutput类里面的rectOfInterest属性注释里面写着下面一段英文
/*!
 @property rectOfInterest
 @abstract
    Specifies a rectangle of interest for limiting the search area for visual metadata.

 @discussion
    The value of this property is a CGRect that determines the receiver's rectangle of interest for each frame of video. The rectangle's origin is top left and is relative to the coordinate space of the device providing the metadata. Specifying a rectOfInterest may improve detection performance for certain types of metadata. The default value of this property is the value CGRectMake(0, 0, 1, 1). Metadata objects whose bounds do not intersect with the rectOfInterest will not be 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)。

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值