AVFoundation 中的自动对焦模式默认是开启的,可以通过设置 AVCaptureDevice 自动对焦的模式来关闭或启用自动对焦功能。在以下示例中,我们使用 AVCaptureDevice 类来访问设备的硬件特性,并将其设置为手动对焦模式。
import AVFoundation
// 获取设备
let captureDevice = AVCaptureDevice.default(for: .video)
// 配置输入输出流
let captureSession = AVCaptureSession()
let videoInput = try? AVCaptureDeviceInput(device: captureDevice!)
let videoOutput = AVCaptureVideoDataOutput()
if captureSession.canAddInput(videoInput!) && captureSession.canAddOutput(videoOutput) {
captureSession.addInput(videoInput!)
captureSession.addOutput(videoOutput)
}
// 关闭自动对焦
do {
try captureDevice!.lockForConfiguration()
captureDevice!.focusMode = .locked
captureDevice!.unlockForConfiguration()
} catch {
// handle error
}
// 开启手动对焦
override func touchesBegan(_ touches: Set, with event: UIEvent?) {
let touchPoint = touches.first!
let screenSize = previewLayer.bounds.size
let focusPoint = CGPoint(x: touchPoint.location(in: previewLayer).y / screenSize.height, y: 1.0 - touchPoint.location(in: previewLayer).x / screenSize.width)
do {
try captureDevice!.lockForConfiguration()
captureDevice!.focusPointOfInterest = focusPoint
captureDevice!.focusMode = .autoFocus
captureDevice!.unlockForConfiguration()
} catch {
// handle error
}
}