gipsey
gipsey

Reputation: 69

How to use Camera2Config.Extender with CameraX

Didn't find any example of setting Camera2Config or Camera2Config.Extender to CameraX.

Could you provide an example of setting these objects to CameraX in order to, for example, get callback method invocations.

Basically I'd like to get the state of Camera in the format of androidx.camera.camera2.impl.Camera.State.

Upvotes: 1

Views: 1985

Answers (1)

amartinz
amartinz

Reputation: 81

I needed this recently too and at time of writing this is the way which worked for me. Please note that this way might stop working, as CameraX is in alpha state.

Basically you take a Config.ExtendableBuilder and pass it in to the constructor of your Camera2Config.Extender before you call build() on it and create the UseCase.

As example i took code from the CameraX sample and adjusted it to use the Camera2Config.Extender.

// Set up the view finder use case to display camera preview
val viewFinderConfigBuilder = PreviewConfig.Builder().apply {
    setLensFacing(lensFacing)
    // We request aspect ratio but no resolution to let CameraX optimize our use cases
    setTargetAspectRatio(screenAspectRatio)
    // Set initial target rotation, we will have to call this again if rotation changes
    // during the lifecycle of this use case
    setTargetRotation(viewFinder.display.rotation)
}

// Create the extender and pass in the config builder we want to extend
val previewExtender = Camera2Config.Extender(viewFinderConfigBuilder)
// Listen to camera state changes
previewExtender.setDeviceStateCallback(object : CameraDevice.StateCallback() {
    // implementation omitted for sake of simplicity
})

// Build your config as usual and create your wanted UseCase with it
val viewFinderConfig = viewFinderConfigBuilder.build()

// Use the auto-fit preview builder to automatically handle size and orientation changes
preview = AutoFitPreviewBuilder.build(viewFinderConfig, viewFinder)

Also i would suggest to not make use of any implementation details and instead use a CameraDevice.StateCallback like in the example above.

Upvotes: 8

Related Questions