【问题标题】:How do I capture QR Code data in specific area of AVCaptureVideoPreviewLayer using Swift?如何使用 Swift 在 AVCaptureVideoPreviewLayer 的特定区域捕获 QR 码数据?
【发布时间】:2015-11-24 22:31:06
【问题描述】:

我正在创建一个 iPad 应用程序,其中一项功能是扫描 QR 码。我有 QR 扫描部分工作,但我遇到的问题是 iPad 屏幕非常大,我将扫描一张纸的小 QR 码,同时可以看到许多 QR 码。我想指定一个较小的显示区域作为唯一可以实际捕获 QR 码的区域,以便用户更轻松地扫描他们想要的特定 QR 码。

我目前制作了一个以页面为中心的带有红色边框的临时 UIView,作为我希望用户扫描 QR 码的示例。它看起来像这样:

我已经四处寻找答案,以找到如何定位 AVCaptureVideoPreviewLayer 的特定区域来收集 QR 码数据的答案,我发现建议将“rectOfInterest”与 AVCaptureMetadataOutput 一起使用。我曾尝试这样做,但是当我将 rectOfInterest 设置为与我用于正确显示的 UIView 相同的坐标和大小时,我无法再扫描/识别任何 QR 码。有人可以告诉我为什么可扫描区域与看到的 UIView 的位置不匹配,我怎样才能让 rectOfInterest 在我添加到屏幕的红色边框内?

这是我目前使用的扫描功能的代码:

func startScan() {
    // Get an instance of the AVCaptureDevice class to initialize a device object and provide the video
    // as the media type parameter.
    let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

    // Get an instance of the AVCaptureDeviceInput class using the previous device object.
    var error:NSError?
    let input: AnyObject! = AVCaptureDeviceInput.deviceInputWithDevice(captureDevice, error: &error)

    if (error != nil) {
        // If any error occurs, simply log the description of it and don't continue any more.
        println("\(error?.localizedDescription)")
        return
    }

    // Initialize the captureSession object.
    captureSession = AVCaptureSession()
    // Set the input device on the capture session.
    captureSession?.addInput(input as! AVCaptureInput)

    // Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
    let captureMetadataOutput = AVCaptureMetadataOutput()
    captureSession?.addOutput(captureMetadataOutput)

    // calculate a centered square rectangle with red border
    let size = 300
    let screenWidth = self.view.frame.size.width
    let xPos = (CGFloat(screenWidth) / CGFloat(2)) - (CGFloat(size) / CGFloat(2))
    let scanRect = CGRect(x: Int(xPos), y: 150, width: size, height: size)

    // create UIView that will server as a red square to indicate where to place QRCode for scanning
    scanAreaView = UIView()
    scanAreaView?.layer.borderColor = UIColor.redColor().CGColor
    scanAreaView?.layer.borderWidth = 4
    scanAreaView?.frame = scanRect

    // Set delegate and use the default dispatch queue to execute the call back
    captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
    captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
    captureMetadataOutput.rectOfInterest = scanRect


    // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
    videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
    videoPreviewLayer?.frame = view.layer.bounds
    view.layer.addSublayer(videoPreviewLayer)

    // Start video capture.
    captureSession?.startRunning()

    // Initialize QR Code Frame to highlight the QR code
    qrCodeFrameView = UIView()
    qrCodeFrameView?.layer.borderColor = UIColor.greenColor().CGColor
    qrCodeFrameView?.layer.borderWidth = 2
    view.addSubview(qrCodeFrameView!)
    view.bringSubviewToFront(qrCodeFrameView!)

    // Add a button that will be used to close out of the scan view
    videoBtn.setTitle("Close", forState: .Normal)
    videoBtn.setTitleColor(UIColor.blackColor(), forState: .Normal)
    videoBtn.backgroundColor = UIColor.grayColor()
    videoBtn.layer.cornerRadius = 5.0;
    videoBtn.frame = CGRectMake(10, 30, 70, 45)
    videoBtn.addTarget(self, action: "pressClose:", forControlEvents: .TouchUpInside)
    view.addSubview(videoBtn)

    view.addSubview(scanAreaView!)

}

更新 我不认为这是重复的原因是因为引用的另一篇文章是在 Objective-C 中,而我的代码是在 Swift 中。对于我们这些刚接触 iOS 的人来说,翻译这两者并不容易。此外,引用的帖子的答案没有显示在解决他的问题的代码中所做的实际更新。他很好地解释了必须使用metadataOutputRectOfInterestForRect 方法来转换矩形坐标,但我似乎仍然无法让这个方法工作,因为我不清楚如果没有例子这应该如何工作。

【问题讨论】:

  • 看起来rectOfInterest 需要在 (0,0) – (1,1) 范围内。您遇到的实际问题是什么?
  • @jtbandes 我想让 rectOfInterest 区域覆盖一个 300 x 300 的正方形区域,并具有与我添加的红色边框 UIView 相同的 x 和 y 坐标,以指示一个可以识别的区域QR 码,并且它是唯一可以识别 QR 码数据的区域。目前,如果我将 rectOfInterest 的大小参数设置为大于 1 的任何值,我将无法再扫描任何内容。我不明白这是为什么......
  • @jtbandes 我不久前看到了那个帖子,老实说,我不太明白如何翻译那个答案来解决我的问题。抱歉,我的背景是网络开发人员,几周前我才开始学习 ios/swift,所以我很难弄清楚如何使用您链接到的帖子中的答案。
  • @Mayerz 我确实最终解决了这个问题。我最终不得不围绕这个问题发布另一个问题以获得帮助,但希望这篇文章现在可以帮助你:stackoverflow.com/questions/32401364/…

标签: ios swift ipad qr-code


【解决方案1】:

在与metedataOutputRectOfInterestForRect 方法斗争了一上午后,我厌倦了它,决定编写自己的转换。

func convertRectOfInterest(rect: CGRect) -> CGRect {
    let screenRect = self.view.frame
    let screenWidth = screenRect.width
    let screenHeight = screenRect.height
    let newX = 1 / (screenWidth / rect.minX)
    let newY = 1 / (screenHeight / rect.minY)
    let newWidth = 1 / (screenWidth / rect.width)
    let newHeight = 1 / (screenHeight / rect.height)
    return CGRect(x: newX, y: newY, width: newWidth, height: newHeight)
}

注意:我有一个带有正方形的图像视图,用于向用户显示扫描的位置,请务必使用imageView.frame 而不是imageView.bounds,以便在屏幕上获得正确的位置。

这对我来说很成功。

【讨论】:

  • 相当有线的分割,1 / (screenWidth / rect.minX) 等于 rect.minX / screenWidth 等等,也可以为 screenRect 和 !rect.isEmpty 添加保护,如果所以返回 {0, 0, 1, 1}
【解决方案2】:
let metadataOutput = AVCaptureMetadataOutput()
metadataOutput.rectOfInterest = convertRectOfInterest(rect: scanRect)

查看其他来源(https://www.jianshu.com/p/8bb3d8cb224e)后, convertRectOfInterest 函数有一个小错误,返回字段应该是:

return CGRect(x: newY, y: newX, width: newHeight, height: newWidth) 

x 和 y、宽度和高度输入应互换以使其正常工作。

【讨论】:

    【解决方案3】:

    需要将UIView的坐标表示的rect转换成AVCaptureVideoPreviewLayer的坐标系:

    captureMetadataOutput.rectOfInterest = videoPreviewLayer.metadataOutputRectConverted(fromLayerRect: scanRect)

    欲了解更多信息:https://stackoverflow.com/a/55778152/6898849

    【讨论】:

      【解决方案4】:
      let scanView = CGRect(x: centerX, y: centerY, width: width, height: height)
      metadataOutput.rectOfInterest = previewLayer.metadataOutputRectConverted(fromLayerRect: scanView)
      

      【讨论】:

        【解决方案5】:

        这对我有用。

        extension AVCaptureVideoPreviewLayer {
            func rectOfInterestConverted(parentRect: CGRect, fromLayerRect: CGRect) -> CGRect {
                let parentWidth = parentRect.width
                let parentHeight = parentRect.height
                let newX = (parentWidth - fromLayerRect.maxX)/parentWidth
                let newY = 1 - (parentHeight - fromLayerRect.minY)/parentHeight
                let width = 1 - (fromLayerRect.minX/parentWidth + newX)
                let height = (fromLayerRect.maxY/parentHeight) - newY
        
                return CGRect(x: newX, y: newY, width: width, height: height)
            }
        }
        

        用法:

            if let rect = videoPreviewLayer?.rectOfInterestConverted(parentRect: self.view.frame, fromLayerRect: scanAreaView.frame) {
                captureMetadataOutput.rectOfInterest = rect
            }
        

        【讨论】:

          【解决方案6】:
          metadataOutput.rectOfInterest = previewLayer.metadataOutputRectConverted(fromLayerRect: yourView.frame)
          

          previewLayer 是 AVCaptureVideoPreviewLayer

          【讨论】:

            猜你喜欢
            • 2017-12-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-01-14
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多