0

I'm learning CameraX API, and CameraXBasic is a office sample code.

CameraFragment.kt in CameraXBasic displays a real camera preview, I hope to add a Switch button to freeze current preview, by which the picture will not change even if I move mobile phone camera lens.

How can I do with CameraX API? Thanks!

CameraFragment.kt

private lateinit var viewFinder: TextureView

private fun bindCameraUseCases() {
    // Get screen metrics used to setup camera for full screen resolution
    val metrics = DisplayMetrics().also { viewFinder.display.getRealMetrics(it) }
    val screenAspectRatio = Rational(metrics.widthPixels, metrics.heightPixels)
    Log.d(TAG, "Screen metrics: ${metrics.widthPixels} x ${metrics.heightPixels}")

    // Set up the view finder use case to display camera preview
    val viewFinderConfig = 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)
    }.build()

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

 ....

 CameraX.bindToLifecycle(
            viewLifecycleOwner, preview, imageCapture, imageAnalyzer)
}
HelloCW
  • 843
  • 22
  • 125
  • 310

1 Answers1

3

Add a PreviewOutputUpdateListener to the Preview, you can then decide wether to update the TextureView:

Java:

preview.setOnPreviewOutputUpdateListener(
        previewOutput -> {
            if(!frozen){
               textureView.setSurfaceTexture(previewOutput.getSurfaceTexture());
            }
});

Kotlin:

preview.setOnPreviewOutputUpdateListener {
    previewOutput: Preview.PreviewOutput? ->
        if(!frozen)
        textureView.setSurfaceTexture(previewOutput.getSurfaceTexture());
}

From Preview Documentation:

The preview use case produces a SurfaceTexture which streams the camera input. It also provides additional information for a View to crop, scale, or rotate for proper display.

The image preview is streamed to this SurfaceTexture when the camera becomes active. The SurfaceTexture can be connected to a TextureView or a GLSurfaceView.

So Preview by itself does not render anything and just provides a Texture to be rendered, it is up to you to decide what to do with this Texture returned by previewOutput.getSurfaceTexture().

Community
  • 1
  • 1
Zohaib Amir
  • 3,482
  • 2
  • 11
  • 29
  • 1
    hi Zohaib! tragically they have removed `setOnPreviewOutputUpdateListener` from 07! Do you know if a replacement? Kindly, fattie – Fattie Mar 11 '21 at 16:10