Set Camera Focus On Tap Point With Swift Set Camera Focus On Tap Point With Swift xcode xcode

Set Camera Focus On Tap Point With Swift


Updated answer from @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                }            }        }    }


Better solution, as it works correctly for all videoGravity modes, also when the preview layer aspect ratio is different from the device ratio:

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}


Updated answer from @Code for Swift 2.

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {    let screenSize = videoView.bounds.size    if let touchPoint = touches.first {        let x = touchPoint.locationInView(videoView).y / screenSize.height        let y = 1.0 - touchPoint.locationInView(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            }        }    }}