iPhone 后置摄像头无法正确对焦

问题描述

我一直在制作 iOS 相机应用程序并尝试解决这个问题两天(但无法解决这个问题)。

我现在正在做的是根据用户点击的位置自动更改焦点和曝光。有时它工作正常(总共可能大约 20%),但大多数情况下它会失败。尤其是当我尝试聚焦远物体(例如 5+ 米)或有两个物体并尝试将一个物体的焦点切换到另一个物体时。下图是一个例子。

enter image description here

enter image description here

黄色方块位于用户点击的位置,即使我在第一张图片中点击了黑色杯子,相机仍然聚焦在红色杯子上。

    override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?) {
        let touchPoint = touches.first! as UITouch
        let focusPoint = touchPoint.location(in: lfView)
        print("focusPoint \(focusPoint)")
    
        showPointOfInterestViewAtPoint(point: focusPoint)
        setFocus(focusMode: .autoFocus,exposureMode: .autoExpose,atPoint: focusPoint,shouldMonitorSujectAreaChange: true)
    }

    func setFocus(focusMode: AVCaptureDevice.FocusMode,exposureMode: AVCaptureDevice.ExposureMode,atPoint devicePoint: CGPoint,shouldMonitorSujectAreaChange: Bool) {
    
        guard let captureDevice = captureDevice else { return }
    
        do {
            try captureDevice.lockForConfiguration()
        } catch let error as NSError { return }
    
        if captureDevice.isFocusPointOfInterestSupported,captureDevice.isFocusModeSupported(focusMode) {
            captureDevice.focusPointOfInterest = devicePoint
            captureDevice.focusMode = focusMode
            print("devicePoint: \(devicePoint)")
        
        }
    
        // other codes in here...
    
        captureDevice.isSubjectAreaChangeMonitoringEnabled = shouldMonitorSujectAreaChange
        captureDevice.unlockForConfiguration()
    }

我在 touchesBegan 函数调用了 setFocus 函数,focusPoint 和 devicePoint 注释都显示相同的坐标,例如 (297.5,88.0)。

当我点击图片中的黑色杯子时,我可以看到 iPhone 相机正在放大和缩小一点,就像我使用认的 iPhone 相机应用程序并尝试对一个物体对焦时一样。所以我猜我的相机应用正试图聚焦在黑色杯子上,但它失败了。

由于这不是错误,我不确定要更改哪个代码。是否有任何线索这里发生了什么以及导致此问题的原因?

稍后添加此部分

我也读过this document,上面写着

属性的 CGPoint 值使用坐标系,其中 {0,0} 是图片区域的左上角,{1,1} 是右下角。

正如我之前写的,devicePoint 的值给了我超过 1,例如 297.5、88.0。这会导致问题吗?

解决方法

多亏了@Artem,我才能够解决这个问题。我需要做的就是将绝对坐标转换为 focusPointOfInterest 中使用的值(min (0,0) 到 max (1,1))。

谢谢你,阿尔特姆!!