限定二维码扫描范围

本文介绍如何使用iOS原生API限定二维码扫描的有效区域。通过设置AVCaptureMetadataOutput的rectOfInterest属性并结合AVCaptureVideoPreviewLayer的方法,可以有效提高特定类型元数据的检测性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值