SurfaceView渲染相机数据
1. 申请权限
<uses-permission android:name="android.permission.CAMERA"/>
2.自定义surfaceView
public class CameraSufaceView extends SurfaceView implements SurfaceHolder.Callback {
private Camera mCamera;
public CameraSufaceView(Context context) {
super(context);
init();
}
public CameraSufaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public CameraSufaceView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
getHolder().addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
L.i("surfaceCreated...");
if (mCamera == null) {
mCamera = Camera.open();//开启相机
try {
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(holder);//相机预览的内容放在 holder
} catch (IOException e) {
ToastUtils.showShort(" 设置预览失败");
e.printStackTrace();
}
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
L.i( "surfaceChanged...");
try {
mCamera.stopPreview();
}catch (Exception e){
e.printStackTrace();
}
mCamera.startPreview();//该方法只有相机开启后才能调用
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
L.i( "surfaceDestroyed...");
if (mCamera != null) {
mCamera.lock();
mCamera.stopPreview();
mCamera.release();//释放相机资源
mCamera = null;
}
}
}
3. 在xml文件中引用该控件即可实现相机数据预览
<FrameLayout 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=".moudle.opengl.MainActivity">
<com.aguai.camerademo.moudle.sufaceview.CameraSufaceView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
网友评论