为 Swift 中的 iOS 相机手动设置曝光

Manually set exposure for iOS camera in Swift

我了解到 iOS 中的摄像头在拍摄视频和照片时会自动连续调整曝光。

问题:

如何关闭相机的自动曝光?

在 Swift 代码中,如何将相机的曝光设置为 "zero" 以便曝光对周围环境完全中性并且不补偿光线?

可以通过设置"AVCaptureExposureMode" 属性来设置曝光模式。 Documentation here.

var exposureMode: AVCaptureDevice.ExposureMode { get set }

您必须考虑的 3 件事。

1) 检查设备是否真的支持 "isExposureModeSupported"

2) 调整曝光前必须"lock for configuration"。 Documentation here.

3) 通过设置 ISO 和持续时间来调整曝光。你不能只将它设置为“0”

ISO:

This property returns the sensor's sensitivity to light by means of a gain value applied to the signal. Only exposure duration values between minISO and maxISO are supported. Higher values will result in noisier images. The property value can be read at any time, regardless of exposure mode, but can only be set using the setExposureModeCustom(duration:iso:completionHandler:) method.

如果您只需要最小、当前和最大曝光值,那么您可以使用以下方法:

Swift 5

    import AVFoundation

    enum Esposure {
        case min, normal, max
        
        func value(device: AVCaptureDevice) -> Float {
            switch self {
            case .min:
                return device.activeFormat.minISO
            case .normal:
                return AVCaptureDevice.currentISO
            case .max:
                return device.activeFormat.maxISO
            }
        }
    }

    func set(exposure: Esposure) {
        guard let device = AVCaptureDevice.default(for: AVMediaType.video) else { return }
        if device.isExposureModeSupported(.custom) {
            do{
                try device.lockForConfiguration()
                device.setExposureModeCustom(duration: AVCaptureDevice.currentExposureDuration, iso: exposure.value(device: device)) { (_) in
                    print("Done Esposure")
                }
                device.unlockForConfiguration()
            }
            catch{
                print("ERROR: \(String(describing: error.localizedDescription))")
            }
        }
    }