Search code examples
androidbarcode-scannerandroid-camera2android-camerax

disable autofocus in android camerax (camera 2)


I'm in project of scanning barcode, so i want to disable auto-focus for improving performance. I tried so many ways but it doesn't work at all. Could anyone give me some help? Thank you.


Solution

  • If you really want to turn off AF, you can do this on CameraX with the Camera2CameraControl class. To do this you have to first bind the use cases you need to the lifecycle which results in a Camera object, you can then use that camera object to get the CameraControl object and then use it to instantiate a Camera2CameraControl which would let you set the focus mode to CameraMetadata.CONTROL_AF_MODE_OFF.

        val camera : Camera = cameraProvider.bindToLifecycle(
                            this,
                            cameraSelector,
                            imagePreview,
                            imageCapture,
                            imageAnalysis
                        )
        
        val cameraControl : CameraControl = camera.cameraControl
        val camera2CameraControl : Camera2CameraControl = Camera2CameraControl.from(cameraControl)
        
        //Then you can set the focus mode you need like this
        val captureRequestOptions = CaptureRequestOptions.Builder()
                    .setCaptureRequestOption(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_OFF)
                    .build()
                camera2CameraControl.captureRequestOptions = captureRequestOptions
    

    This was tested on the latest CameraX's "1.0.0-rc03" build.