ios - 如何使用 Swift 在 AVCaptureVideoPreviewLayer 的特定区域捕获二维码数据?

标签 ios swift ipad qr-code

我正在创建一个 iPad 应用程序,其中一项功能是扫描二维码。我有 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 方法转换矩形坐标留下了很好的解释,但我似乎仍然无法使这种方法起作用,因为我不清楚如果没有示例它应该如何起作用.

最佳答案

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 ,用于向用户显示要扫描的位置,请务必按顺序使用 imageView.frame 而不是 imageView.bounds获取屏幕上的正确位置。

这对我来说一直很成功。

关于ios - 如何使用 Swift 在 AVCaptureVideoPreviewLayer 的特定区域捕获二维码数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32301933/

相关文章:

ios - RedPark 无法从串行端口 : UIViewController vs. UINavigationController 读取数据

ios - 为 iTunes 创建通用应用程序?

ios - 检查 iPad 是否能够路由到 Internet

ios - 适用于 IOS 7 的框架 Google map

ios - 如何在 iOS 上的 Google map 中徒手绘制?

ios - uitableview如何动态解析数据多单元格

arrays - 向下转换多个协议(protocol) Array<protocol<P1, P2>> 到 Array<P1>

swift - firebase google 登录后如何关闭 View

ios - Swift 3 到 4 - '#selector' 的参数引用未公开给 Objective-C 的实例方法 'handleScreenTap(sender:)'

ios - 如何在 iPhone 应用程序中集成 SIRI?