ios - 使用 Swift 将相机焦点设置在点击点上

标签 ios xcode swift camera avfoundation

用于在 swift 中使用相机的 API 似乎有所不同,我很难将相机聚焦在一个点上。当用户点击屏幕时,我希望相机聚焦在那个点上

这是我的代码:

 func focusCamera(point:CGPoint)
    {
        var screenRect:CGRect = bounds
        var focusX = Float(point.x/screenRect.width)
        var focusY = Float(point.y/screenRect.height)

        _currentDevice.lockForConfiguration(nil)
        _currentDevice.setFocusModeLockedWithLensPosition(focusX)
        {
            time in
            self._currentDevice.unlockForConfiguration()
        }

        _currentDevice.setFocusModeLockedWithLensPosition(focusY)
        {
                time in
                self._currentDevice.unlockForConfiguration()
        }
    }

但是好像不行。

我们非常欢迎任何建议!

最佳答案

@ryantxr 对 Swift 3 的更新回答:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let screenSize = videoView.bounds.size
        if let touchPoint = touches.first {
            let x = touchPoint.location(in: videoView).y / screenSize.height
            let y = 1.0 - touchPoint.location(in: videoView).x / screenSize.width
            let focusPoint = CGPoint(x: x, y: y)

            if let device = captureDevice {
                do {
                    try device.lockForConfiguration()

                    device.focusPointOfInterest = focusPoint
                    //device.focusMode = .continuousAutoFocus
                    device.focusMode = .autoFocus
                    //device.focusMode = .locked
                    device.exposurePointOfInterest = focusPoint
                    device.exposureMode = AVCaptureExposureMode.continuousAutoExposure
                    device.unlockForConfiguration()
                }
                catch {
                    // just ignore
                }
            }
        }
    }

关于ios - 使用 Swift 将相机焦点设置在点击点上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26682450/

相关文章:

ios - 更改自定义文本字段背景颜色和文本颜色 IOS Swift

ios - 无法在 iOS 设备上打开 pkpass

ios - 即使更新了表格 View 单元格,如何在表格 View 中保留表格 View 单元格的编辑模式?

iphone - 为什么我的 ASIHTTPRequest 文件显示 ARC 错误?

arrays - Swift:使用&符号(&)引用对象的属性导致编译器错误

ios - 发送APN返回BadDeviceToken,DeviceToken格式应该是什么?

python - 如何在 XCode 4.6 中配置 Python?

swift - XCAssets PNG 白色空间

json - Swift Alamofire JSON 响应有括号

ios - SwiftUI - NavigationView 中的内存泄漏