今天来说讲使用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