iPhone设备包含多个后置镜头,怎么选择合适的镜头进行使用?通常情况下,默认使用广角镜头.但是在iPhone14 Pro/Pro Max,iPhone15 Pro/Pro Max设备下,使用默认广角镜头进行扫码/身份证识别时,会出现无法对焦的情况.怎么才能不根据设备判断来自动切换不同的镜头呢
方案
extension AVCaptureDevice {
class func getBestBackCameraDevice() -> AVCaptureDevice? {
var device: AVCaptureDevice?
if #available(iOS 13.0, *) {
device = AVCaptureDevice.default(.builtInTripleCamera, for: .video, position: .back)
if device == nil {
device = AVCaptureDevice.default(.builtInDualWideCamera, for: .video, position: .back)
}
if device == nil {
device = AVCaptureDevice.default(.builtInDualCamera, for: .video, position: .back)
}
}
if device == nil {
device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)
}
return device
}
}
系统会根据机型自动选择镜头.包含超广角的设备系统默认使用的还是超广角镜头.由于12/12pro等机型不支持微距模式,扫码时效果反而不如广角镜头好.要通过设置默认使用广角镜头.设置代码如下:
extension AVCaptureDevice {
var neutralZoomFactor: CGFloat {
if #available(iOS 13.0, *) {
if let indexOfWideAngle = self.constituentDevices.firstIndex(where: { $0.deviceType == .builtInWideAngleCamera }) {
if let zoomFactor = self.virtualDeviceSwitchOverVideoZoomFactors[safe: indexOfWideAngle - 1] {
return CGFloat(zoomFactor.doubleValue)
}
}
}
return 1.0
}
}
//设置:
let device = AVCaptureDevice.getBestBackCameraDevice()
if let device {
do {
try device.lockForConfiguration()
defer {
device.unlockForConfiguration()
}
device.videoZoomFactor = device?.neutralZoomFactor ?? 1.0
} catch let error {
print(error)
}
}
其实就是获取到广角镜头的焦距,设置一下. 支持微距功能的设备会自动切换到超广角镜头进行识别,不支持的就使用的默认的广角镜头进行识别. 如果想要根据手势设置缩放比例,也通过设置videoZoomFactor来切换.系统会根据不同的值来进行镜头的切换.