Google is committed to advancing racial equity for Black communities. See how.

PreviewView

public final class PreviewView
extends FrameLayout

java.lang.Object
   ↳ android.view.View
     ↳ android.view.ViewGroup
       ↳ android.widget.FrameLayout
         ↳ androidx.camera.view.PreviewView


Custom View that displays the camera feed for CameraX's Preview use case.

This class manages the preview Surface's lifecycle. It internally uses either a TextureView or SurfaceView to display the camera feed, and applies required transformations on them to correctly display the preview, this involves correcting their aspect ratio, scale and rotation.

If PreviewView uses a SurfaceView to display the preview stream, be careful when overlapping a View that's initially not visible (either View.INVISIBLE or View.GONE) on top of it. When the SurfaceView is attached to the display window, it calls ViewParent.requestTransparentRegion(View) which requests a computation of the transparent regions on the display. At this point, the View isn't visible, causing the overlapped region between the SurfaceView and the View to be considered transparent. Later if the View becomes visible, it will not be displayed on top of SurfaceView. A way around this is to call ViewParent.requestTransparentRegion(View) right after making the View visible, or initially hiding the View by setting its opacity to 0, then setting it to 1.0F to show it.

Summary

Nested classes

enum PreviewView.ImplementationMode

The implementation mode of a PreviewView

enum PreviewView.ScaleType

Options for scaling the preview vis-à-vis its container PreviewView

enum PreviewView.StreamState

Definitions for the preview stream state. 

Inherited constants

Inherited fields

Public constructors

PreviewView(Context context)
PreviewView(Context context, AttributeSet attrs)
PreviewView(Context context, AttributeSet attrs, int defStyleAttr)
PreviewView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)

Public methods

Bitmap getBitmap()

Returns a Bitmap representation of the content displayed on the PreviewView, or null if the camera preview hasn't started yet.

CameraController getController()

Get the CameraController.

PreviewView.ImplementationMode getImplementationMode()

Returns the PreviewView.ImplementationMode.

MeteringPointFactory getMeteringPointFactory()

Gets the MeteringPointFactory for the camera currently connected to the PreviewView, if any.

LiveData<PreviewView.StreamState> getPreviewStreamState()

Gets a LiveData for the preview PreviewView.StreamState.

PreviewView.ScaleType getScaleType()

Returns the PreviewView.ScaleType currently applied to the preview.

Preview.SurfaceProvider getSurfaceProvider()

Gets a Preview.SurfaceProvider to be used with Preview.setSurfaceProvider(Executor, Preview.SurfaceProvider).

ViewPort getViewPort()

Gets a ViewPort based on the current status of PreviewView.

ViewPort getViewPort(int targetRotation)

Gets a ViewPort with custom target rotation.

boolean onTouchEvent(MotionEvent event)
boolean performClick()
void setController(CameraController cameraController)

Sets the CameraController.

void setImplementationMode(PreviewView.ImplementationMode implementationMode)

Sets the PreviewView.ImplementationMode for the PreviewView.

void setScaleType(PreviewView.ScaleType scaleType)

Applies a PreviewView.ScaleType to the preview.

Protected methods

void onAttachedToWindow()
void onDetachedFromWindow()

Inherited methods

Public constructors

PreviewView

public PreviewView (Context context)

Parameters
context Context

PreviewView

public PreviewView (Context context, 
                AttributeSet attrs)

Parameters
context Context

attrs AttributeSet

PreviewView

public PreviewView (Context context, 
                AttributeSet attrs, 
                int defStyleAttr)

Parameters
context Context

attrs AttributeSet

defStyleAttr int

PreviewView

public PreviewView (Context context, 
                AttributeSet attrs, 
                int defStyleAttr, 
                int defStyleRes)

Parameters
context Context

attrs AttributeSet

defStyleAttr int

defStyleRes int

Public methods

getBitmap

public Bitmap getBitmap ()

Returns a Bitmap representation of the content displayed on the PreviewView, or null if the camera preview hasn't started yet.

The returned Bitmap uses the Bitmap.Config.ARGB_8888 pixel format and its dimensions are the same as this view's.

Do not invoke this method from a drawing method (View.onDraw(Canvas) for instance).

If an error occurs during the copy, an empty Bitmap will be returned.

If the preview hasn't started yet, the method may return null or an empty Bitmap. Use getPreviewStreamState() to get the PreviewView.StreamState and wait for PreviewView.StreamState.STREAMING to make sure the preview is started.

Returns
Bitmap A Bitmap.Config.ARGB_8888 Bitmap representing the content displayed on the PreviewView, or null if the camera preview hasn't started yet.

getController

public CameraController getController ()

Get the CameraController.

Returns
CameraController

getMeteringPointFactory

public MeteringPointFactory getMeteringPointFactory ()

Gets the MeteringPointFactory for the camera currently connected to the PreviewView, if any.

The returned MeteringPointFactory is capable of creating MeteringPoints from (x, y) coordinates in the PreviewView. This conversion takes into account its PreviewView.ScaleType. The MeteringPointFactory is automatically adjusted if the PreviewView layout or the PreviewView.ScaleType changes.

The MeteringPointFactory returns invalid MeteringPoint if the preview is not ready, or the PreviewView dimension is zero. The invalid MeteringPoint will cause CameraControl.startFocusAndMetering(FocusMeteringAction) to fail but it won't crash the application. Wait for the PreviewView.StreamState.STREAMING state to make sure the preview is ready.

Returns
MeteringPointFactory a MeteringPointFactory

getPreviewStreamState

public LiveData<PreviewView.StreamState> getPreviewStreamState ()

Gets a LiveData for the preview PreviewView.StreamState.

There are two preview stream states, PreviewView.StreamState.IDLE and PreviewView.StreamState.STREAMING. PreviewView.StreamState.IDLE indicates the preview is currently not visible and streaming is stopped. PreviewView.StreamState.STREAMING means the preview is streaming or is about to start streaming. This state guarantees the preview is visible only when the PreviewView.ImplementationMode is PreviewView.ImplementationMode.COMPATIBLE. When in PreviewView.ImplementationMode.PERFORMANCE mode, it is possible the preview becomes visible slightly after the state changes to PreviewView.StreamState.STREAMING.

Apps that require a precise signal for when the preview starts should set the implementation mode to PreviewView.ImplementationMode.COMPATIBLE.

Returns
LiveData<PreviewView.StreamState> A LiveData of the preview's PreviewView.StreamState. Apps can get the current state with LiveData.getValue(), or register an observer with LiveData.observe(LifecycleOwner, Observer) .

getScaleType

public PreviewView.ScaleType getScaleType ()

Returns the PreviewView.ScaleType currently applied to the preview.

The default value is PreviewView.ScaleType.FILL_CENTER.

Returns
PreviewView.ScaleType The PreviewView.ScaleType currently applied to the preview.

getSurfaceProvider

public Preview.SurfaceProvider getSurfaceProvider ()

Gets a Preview.SurfaceProvider to be used with Preview.setSurfaceProvider(Executor, Preview.SurfaceProvider). This allows the camera feed to start when the Preview use case is bound to a lifecycle.

The returned Preview.SurfaceProvider will provide a preview Surface to the camera that's either managed by a TextureView or SurfaceView depending on the PreviewView.ImplementationMode and the device's attributes (e.g. API level, camera hardware support level).

Returns
Preview.SurfaceProvider A Preview.SurfaceProvider to attach to a Preview use case.

getViewPort

public ViewPort getViewPort ()

Gets a ViewPort based on the current status of PreviewView.

Returns a ViewPort instance based on the PreviewView's current width, height, layout direction, scale type and display rotation. By using the ViewPort, all the UseCases in the UseCaseGroup will have the same output image that also matches the aspect ratio of the PreviewView.

Returns
ViewPort null if the view is not currently attached or the view's width/height is zero.

getViewPort

public ViewPort getViewPort (int targetRotation)

Gets a ViewPort with custom target rotation.

Returns a ViewPort instance based on the PreviewView's current width, height, layout direction, scale type and the given target rotation.

Use this method if Preview's desired rotation is not the default display rotation. For example, when remote display is in use and the desired rotation for the remote display is based on the accelerometer reading. In that case, use OrientationEventListener to obtain the target rotation and create ViewPort as following:

OrientationEventListener.ORIENTATION_UNKNOWN: orientation == -1

Surface.ROTATION_0: orientation >= 315 || orientation < 45

Surface.ROTATION_90: orientation >= 225 && orientation < 315

Surface.ROTATION_180: orientation >= 135 && orientation < 225

Surface.ROTATION_270: orientation >= 45 && orientation < 135

Once the target rotation is obtained, use it with Preview.setTargetRotation(int) to update the rotation. Example:


 Preview preview = new Preview.Builder().setTargetRotation(targetRotation).build();
 ViewPort viewPort = previewView.getViewPort(targetRotation);
 UseCaseGroup useCaseGroup =
     new UseCaseGroup.Builder().setViewPort(viewPort).addUseCase(preview).build();
 cameraProvider.bindToLifecycle(lifecycleOwner, cameraSelector, useCaseGroup);
 

Note that for non-display rotation to work, the mode must be set to PreviewView.ImplementationMode.COMPATIBLE.

Parameters
targetRotation int: A rotation value, expressed as one of Surface.ROTATION_0, Surface.ROTATION_90, Surface.ROTATION_180, or Surface.ROTATION_270.

Returns
ViewPort null if the view's width/height is zero.

onTouchEvent

public boolean onTouchEvent (MotionEvent event)

Parameters
event MotionEvent

Returns
boolean

performClick

public boolean performClick ()

Returns
boolean

setController

public void setController (CameraController cameraController)

Sets the CameraController.

Once set, the controller will use PreviewView to display camera preview feed. It also uses the PreviewView's layout dimension to set the crop rect for all the use cases so that the output from other use cases match what the end user sees in PreviewView. It also enables features like tap-to-focus and pinch-to-zoom.

Setting it to null or to a different CameraController stops the previous CameraController from working. The previous CameraController will remain detached until it's set on the PreviewView again.

Parameters
cameraController CameraController

Throws
IllegalArgumentException If the CameraController's camera selector is unable to resolve a camera to be used for the enabled use cases.

See also:

setImplementationMode

public void setImplementationMode (PreviewView.ImplementationMode implementationMode)

Sets the PreviewView.ImplementationMode for the PreviewView.

PreviewView displays the preview with a TextureView when the mode is PreviewView.ImplementationMode.COMPATIBLE, and tries to use a SurfaceView if it is PreviewView.ImplementationMode.PERFORMANCE when possible, which depends on the device's attributes (e.g. API level, camera hardware support level). If not set, the default mode is PreviewView.ImplementationMode.PERFORMANCE.

This method needs to be called before the Preview.SurfaceProvider is set on Preview. Once changed, Preview.SurfaceProvider needs to be set again. e.g. preview.setSurfaceProvider(previewView.getSurfaceProvider()).

Parameters
implementationMode PreviewView.ImplementationMode

setScaleType

public void setScaleType (PreviewView.ScaleType scaleType)

Applies a PreviewView.ScaleType to the preview.

Once applied, the transformation will take immediate effect. This value can also be set in the layout XML file via the app:scaleType attribute.

The default value is PreviewView.ScaleType.FILL_CENTER.

Parameters
scaleType PreviewView.ScaleType: A PreviewView.ScaleType to apply to the preview.

Protected methods

onAttachedToWindow

protected void onAttachedToWindow ()

onDetachedFromWindow

protected void onDetachedFromWindow ()