func scaning(){ //获取摄像设备
guard let device = AVCaptureDevice.default(for: .video) else { return } //输入流
let input: AVCaptureDeviceInput
do{
input = try AVCaptureDeviceInput.init(device: device)
}catch{
return
} //输出流
let output = AVCaptureMetadataOutput()
//设置代理,并且在主线程刷新
output.setMetadataObjectsDelegate(self, queue:DispatchQueue.main)
output.rectOfInterest = CGRect(x: kScreenWidth/2-100, y: kScreenHeight/2-100, width: 200/kScreenWidth, height: 200/kScreenHeight) //初始化链接对象 / 高质量采集率
session = AVCaptureSession()
session.canSetSessionPreset(.high) if session.canAddInput(input) {
session.addInput(input)
}else {
failed()
return
} if session.canAddOutput(output) {
session.addOutput(output)
}else {
failed()
return
} //先添加输入输出流,后设置支持的扫码所支持的格式,不然报错
//设置扫码支持的编码格式
output.metadataObjectTypes = [.ean8, .ean13, .code128, .qr] preview = AVCaptureVideoPreviewLayer(session: session)
preview.videoGravity = .resizeAspectFill
preview.connection?.videoOrientation = .portrait
preview.frame = view.bounds
view.layer.insertSublayer(preview, at: 0) //开始捕捉
session.startRunning()
}
修改:output 的 restOfInterest应该为:
output.rectOfInterest = CGRect(x: (kScreenHeight/2-100)/kScreenHeight, y: (kScreenWidth/2-100)/kScreenWidth, width: 200/kScreenHeight, height: 200/kScreenWidth)