使用Swift将相机焦点设置在Tap point上

Agg*_*sor 7 xcode camera avfoundation ios swift

在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()
        }
    }
Run Code Online (Sandbox Code Playgroud)

但它似乎没有用.

任何建议都非常欢迎!

Oxy*_*lax 12

来自@ryantxr for 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
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)


fab*_*abb 6

更好的解决方案,因为它适用于所有videoGravity模式,也适用于预览层纵横比与设备比例不同的情况:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    guard let touchPoint = touches.first else { return }

    // precondition: the videoView contains the previewLayer, and the frames of the two are being kept equal
    let touchPointInPreviewLayer = touchPoint.location(in: videoView)
    let focusPoint = previewLayer.captureDevicePointOfInterest(for: touchPointInPreviewLayer)

    // etc
}
Run Code Online (Sandbox Code Playgroud)


Agg*_*sor 1

事实证明它非常简单:

_currentDevice.lockForConfiguration(nil)
_currentDevice.focusPointOfInterest = tap.locationInView(self)
_currentDevice.unlockForConfiguration()
Run Code Online (Sandbox Code Playgroud)

  • 您能否提供更多信息...我是初学者,我不知道这段代码放在哪里 (3认同)