Apple原装扫描二维码指定区域

之前记录了用Apple原装的AVFoundationo类库扫描二维码:http://www.cnblogs.com/foxting/p/4733226.html,此篇记录下如何设置扫描区域。

 AVCaptureMetadataOutput有一个属性rectOfInterest,设置你的区域即可。

先把Video区域设置成全屏的:self.layer?.frame = self.view.bounds

看下rectOfInterest的注释会知道它的区域大小是先设置top再设置left,有效范围为(0,0,1,1)

@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.

键入以下代码

let x = (self.view.bounds.size.width - 268) / 2
let beginningX = x / self.view.bounds.width
let beginningY = 106 / self.view.bounds.height
let width = 268 / self.view.bounds.width
let height = 268 / self.view.bounds.height
let interestedRect = CGRectMake(beginningY, beginningX, height, width)

let output = AVCaptureMetadataOutput()
output.rectOfInterest = interestedRect

 实现的效果还是可以的,此设置还是蛮方便的。上图咯:

原文地址:https://www.cnblogs.com/foxting/p/4961254.html