今天來說講使用camera接口和TextureSurface兩個來進行預覽android
先看xml:app
<?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>
xml裏面就只有一個TextureView,這個就是用來預覽的控件。ide
再看代碼的實現:this
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) { } }
代碼裏面首先是實例化camera接口,而且打開camera.設置TextureView的監聽,這個監聽是爲了在合適的時間打開預覽以及釋放camera.從代碼中能夠看出在onSurfaceTextureAvailable
裏面首先將surfaceture設置給camera,而後再預覽。這個和上一篇的suerface的顯示很像,在上一篇中是設置SurfaceHolder,最終的目的其實都是將顯示的數據畫在surface上面。code