bug: 使用 iOS 系统方法进行二维码扫描,扫描区域的问题

项目里用到了扫描,出现了bug:感觉就是把二维码正好框在扫描框里扫不出来,然后把镜头离二维码拉远,扫描速度很慢,但是能扫描出来。网上找了下代码,发现也没啥哪里不一样,感觉很坑啊,后面发现不设置

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.

 */

@property(nonatomic) CGRect rectOfInterest NS_AVAILABLE_IOS(7_0);

 

@ property rectOfInterest
@ abstract
指定一个矩形,用于限制可视元数据的搜索区域。
@discussion
这个属性的值是一个CGRect,每一帧视频的接收都跟这个矩形区域有关。矩形的原点在左上角,相对于提供元数据的设备的坐标空间。指定rectOfInterest可以提高特定类型元数据的检测性能。此属性的默认值是CGRectMake(0,0,1,1),其边界不与rectOfInterest相交的元数据对象将不会返回。

 

但是这么设置之后发现不是那么回事。找了下资料:

AVCaptureMetadataOutput 中的属性rectOfInterest 看起来是CGRect类型, 结果让你填写一个比例, 当你填写比例是你会发现还是有各种问题,  最后总结一下, 加入你的屏幕的frame 为  x , y,  w, h,  你要设置的矩形快的frame  为  x1, y1, w1, h1.   那么你的 rectOfInterest 应该设置为  CGRectMake(y1/y, x1/x, h1/h, w1/w)

 

举例子:

我们的扫描区域案图左边的原点来说是,CGRectMake((kScreenWidth-200)/2,(kScreenHeight-200)/2,200,200);

那我们设置的时候呢:

outPut.rectOfInterest = CGRectMake(((kScreenHeight-200)/2)/kScreenHeight,  ((kScreenWidth-200)/2)/kScreenWidth,  200/kScreenHeight,  200/kScreenWidth);

 

就是原坐标点从左边的这样变成右边的这样了。而且还要转换成比例。

 

 

 

 

另外还有种方法,就是调系统的转换方法,但是这个方法要在[_session startRunning] 之后才管用,代码如下:

 CGRect intertRect = [_preview metadataOutputRectOfInterestForRect:CGRectMake((kScreenWidth-200)/2, (kScreenHeight-200)/2, 200, 200)];

 [_output setRectOfInterest:intertRect];

 

我打印了下这个rect,输出的值差不多。差值基本可以忽略。

 

   //第一种方法,直接设置:
    
    CGRect test = CGRectMake(((kScreenHeight-200)/2)/kScreenHeight,((kScreenWidth-200)/2)/kScreenWidth,200/kScreenHeight,200/kScreenWidth);
    NSLog(@"test:%@",NSStringFromCGRect(test));
    
    
    //第二种方法,调系统方法设置,但是要在startRunning后才有效果:
    
    // Start
    [_session startRunning];
    
    CGRect intertRect = [_preview metadataOutputRectOfInterestForRect:CGRectMake((kScreenWidth-200)/2, (kScreenHeight-200)/2, 200, 200)];
    [_output setRectOfInterest:intertRect];
    NSLog(@"intertRect:%@",NSStringFromCGRect(intertRect));
    
    //打印结果:
   
   test:{{0.3641304347826087, 0.25845410628019322}, {0.27173913043478259, 0.48309178743961351}}

   intertRect:{{0.36413043478260865, 0.25845410628019327}, {0.27173913043478259, 0.48309178743961356}}

 

posted @ 2018-08-26 11:32  milaliu99  Views(287)  Comments(0)    收藏  举报