Android Dev Summit, October 23-24: two days of technical content, directly from the Android team. Sign-up for livestream updates.

Implement a preview

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.

Implementation

The following sample shows how to use PreviewOutput:

Kotlin

val previewConfig = PreviewConfig.Builder().build()
val preview = Preview(previewConfig)

preview.setOnPreviewOutputUpdateListener {
    previewOutput: Preview.PreviewOutput? ->
        // Your code here. For example, use previewOutput?.getSurfaceTexture()
        // and post to a GL renderer.
}

CameraX.bindToLifecycle(this as LifecycleOwner, preview)

Java

PreviewConfig config = new PreviewConfig.Builder().build();
Preview preview = new Preview(config);

preview.setOnPreviewOutputUpdateListener(
    new Preview.OnPreviewOutputUpdateListener() {
        @Override
        public void onUpdated(Preview.PreviewOutput previewOutput) {
            // Your code here. For example, use previewOutput.getSurfaceTexture()
            // and post to a GL renderer.
        };
});

CameraX.bindToLifecycle((LifecycleOwner) this, preview);

Use CameraView

CameraX provides a CameraView class that uses a Preview to implement a more convenient View API. The View API automatically scales, crops, and rotates the image data.

Torch mode, focus, and zoom controls are implemented in this preview. Unlike use cases, where configuration is set at creation, you can set these controls dynamically, while the use case is in operation.

Additional resources

To learn more about CameraX, consult the following additional resources.

Codelab

  • Getting Started with CameraX
  • Code sample

  • Official CameraX sample app