Preview of camera+TextureSurface at the beginning of live video

Keywords: Mobile Android xml encoding

Today, I'll talk about using camera interface and TextureSurface to preview

First look at xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".camera_texture_activity">
<TextureView
    android:id="@+id/preview_textureview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>

There is only one TextureView in xml, which is the control for preview.

Look at the implementation of the code:

package com.example.amei.cameraexample;

import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.TextureView;

public class camera_texture_activity extends AppCompatActivity implements TextureView.SurfaceTextureListener {
    private static final String TAG = "cameraTexture";
    private TextureView mTextureView = null;
    private Camera mCamera = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_texture_activity);
        mTextureView = findViewById(R.id.preview_textureview);


        mCamera = Camera.open(0);
        mTextureView.setSurfaceTextureListener(this);
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
        try{
            mCamera.setPreviewTexture(surfaceTexture);
            mCamera.startPreview();
        }catch (Exception e)
        {

        }


    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) {

    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
        mCamera.release();
        return false;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {

    }
}

In the code, first instantiate the camera interface, and open the camera. Set TextureView listening to open preview and release the camera at the right time. From the code, you can see that in onSurfaceTextureAvailable, first set the surface to camera, and then preview. This is very similar to the display of the surface in the previous article. In the previous article, you set the SurfaceHolder. The ultimate goal is to draw the displayed data on the surface.

Posted by driverdave on Fri, 06 Dec 2019 03:19:57 -0800