Android TextureView+SurfaceTexture实现相机预览

Posted 王睿丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android TextureView+SurfaceTexture实现相机预览相关的知识,希望对你有一定的参考价值。

androidManifest.xml

    <uses-permission android:name="android.permission.RECORD_AUDIO"/><!--音频录制权限-->
    <uses-permission android:name="android.permission.CAMERA"/><!--摄像头权限-->
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/><!--存储权限-->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

MainActivity .java

import android.Manifest;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.Gravity;
import android.view.TextureView;
import android.view.View;
import android.widget.FrameLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import java.io.IOException;

public class MainActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener 
    private Camera mCamera;
    private TextureView mTextureView;


    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);

        /**
         * 在 Android 6.0 以上需要动态添加权限
         */
        ActivityCompat.requestPermissions(this,
                new String[]Manifest.permission.CAMERA,Manifest.permission.RECORD_AUDIO,
                100);

        mTextureView = new TextureView(this);
        mTextureView.setSurfaceTextureListener(this);
        mTextureView.setScaleX(-1f);
        setContentView(mTextureView);
    

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) 
        mCamera = Camera.open(1);
        Camera.Size previewSize = mCamera.getParameters().getPreviewSize();
        mTextureView.setLayoutParams(new FrameLayout.LayoutParams(
                previewSize.width, previewSize.height, Gravity.CENTER));

        try 
            mCamera.setPreviewTexture(surface);
         catch (IOException t) 
        

        mCamera.startPreview();

    

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) 
        // Ignored, the Camera does all the work for us
    

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) 
        mCamera.stopPreview();
        mCamera.release();
        return true;
    

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture surface) 
        // Update your view here!
    

以上是关于Android TextureView+SurfaceTexture实现相机预览的主要内容,如果未能解决你的问题,请参考以下文章

Android使用TextureView播放视频

Android Camera2 拍照——使用TextureView

android - 使用没有surfaceview或textureview的相机

Android之TextureView浅析

Android 中Textureview和SurfaceView使用问题总结

玩转Android Camera开发:使用TextureView和SurfaceTexture预览Camera 基础拍照demo