Search code examples
javaandroidandroid-layoutandroid-fragmentsandroid-camera2

Camera2 API Make Preview Fill Entire View


I am using the Camera2Basic example from Google Samples (https://github.com/googlesamples/android-Camera2Basic) to display a camera preview inside a fragment. This fragment contains a RelativeLayout and a custom AutoFitTextureView. The latter can be found on the link above. I have adjusted the layout to center the preview and remove control buttons:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/camera_rel">

    <uk.co.deluxe_digital.messngr.AutoFitTextureView
    android:id="@+id/texture"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true" />

</RelativeLayout>

I have three total fragments that are displayed within a ViewPager. I did make some small changes to the Camera2BasicFragment to make it an android.support.v4.app.Fragment to work with my ViewPager and remove the buttons.

What I would like is to make the camera preview fill the entire screen. This is possible by stretching the preview image. That is not what I want. Does anyone know a way of scaling up the preview or TextureView so that the height of the preview matches the container even if the sides are cropped off. I would like it to fill the view and maintain aspect ratio. This would mean that some of the preview at either side is lost, but that is okay.

This is what I currently have: current incorrect display of camera preview

The FloatingActionButton takes care of capturing the image. That is on the main parent activity.

Even if you can point me in the right direction to working this out, that would be a huge help!


Solution

  • AutoFitTextureView extends TextureView to keep aspect ratio. If you want to fill the entire scree, just use:

    <TextureView
        android:id="@+id/texture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
     />