您的位置:首页 > 移动开发 > IOS开发

限定二维码扫描范围

2017-06-19 17:14 120 查看
使用iOS原生的二维码扫描,如何限定扫描范围,你可能已经知道,通过设定AVCaptureMetadataOutput的rectOfInterest来限定范围,对,就是这个属性。

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.

这是官方对这个属性的说明,是不是有点晕,这个rect和平常理解的那个rect有点区别,不过不用担心自己不会计算,AVCaptureVideoPreviewLayer的metadataOutputRectOfInterestForRect方法可以帮你计算出来。

AVCaptureMetadataOutput rectOfInterest is expressed as a CGRect where {0,0} represents the top left of the picture area, and {1,1} represents the bottom right on an unrotated picture. This convenience method converts a rectangle in the coordinate space of the receiver to a rectangle of interest in the coordinate space of an AVCaptureMetadataOutput whose AVCaptureDevice is providing input to the receiver. The conversion takes frame size and videoGravity into consideration.

但是这个方法用的时机要对。

AVCaptureSession startRunning
之前用,结果始终是
{0,0,0,0}


在收到
AVCaptureInputPortFormatDescriptionDidChangeNotification
之后调用,我试了一下,在iOS8-iOS10上都没有问题,但是在iOS7结果始终是
{0,0,0,0}


最后尝试在
AVCaptureSession startRunning
之后调用,成功,iOS7-iOS10都没有问题。

所以正确的使用方式是

[session startRunning];
CGRect scopeRect = CGRectMake(x, y, width, height);//要限定的范围
output.rectOfInterest = [previewLayer metadataOutputRectOfInterestForRect:scopeRect];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 二维码 范围 限定