user4806509
user4806509

Reputation: 3011

Manually set exposure for iOS camera in Swift

I understand that the camera in iOS automatically adjusts exposure continuously when capturing video and photos.

Questions:

How can I turn off the camera's automatic exposure?

In Swift code, how can I set the exposure for the camera to "zero" so that exposure is completely neutral to the surroundings and not compensating for light?

Upvotes: 5

Views: 9245

Answers (2)

Alexander Volkov
Alexander Volkov

Reputation: 8387

If you need only min, current and max exposure values, then you can use the following:

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))")
            }
        }
    }

Upvotes: 3

Pochi
Pochi

Reputation: 13459

You can set the exposure mode by setting the "AVCaptureExposureMode" property. Documentation here.

var exposureMode: AVCaptureDevice.ExposureMode { get set }

3 things you gotta take into consideration.

1) Check if the device actually supports this with "isExposureModeSupported"

2) You have to "lock for configuration" before adjusting the exposure. Documentation here.

3) The exposure is adjusted by setting an ISO and a duration. You can't just set it to "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.

Upvotes: 5

Related Questions