Android Camera2 实现预览功能实现预览功能
1. 概述概述
最近在做一些关于人脸识别的项目,需要用到 Android 相机的预览功能。网上查阅相关资料后,发现 Android 5.0 及以后的版
本中,原有的 Camera API 已经被 Camera2 API 所取代。
全新的 Camera2 在 Camera 的基础上进行了改造,大幅提升了 Android 系统的拍照功能。它通过以下几个类与方法来实现相
机预览时的工作过程:
•CameraManager :摄像头管理器,主要用于检测系统摄像头、打开系统摄像头等;
•CameraDevice : 用于描述系统摄像头,可用于关闭相机、创建相机会话、发送拍照请求等;
•CameraCharacteristics :用于描述摄像头所支持的各种特性;
•CameraCaptureSession :当程序需要预览、拍照时,都需要先通过 CameraCaptureSession 来实现。该会话通过调用方法
setRepeatingRequest() 实现预览;
•CameraRequest :代表一次捕获请求,用于描述捕获图片的各种参数设置;
•CameraRequest.Builder :负责生成 CameraRequest 对象。
2. 相机预览相机预览
下面通过源码来讲解如何使用 Camera2 来实现相机的预览功能。
2.1 相机权限设置相机权限设置
<uses-permission android:name="android.permission.CAMERA" />
2.2 App 布局布局
•activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
tools:context=".MainActivity">
</FrameLayout>
•fragment_camera.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CameraFragment">
<com.lightweh.camera2preview.AutoFitTextureView
android:id="@+id/textureView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
2.3 相机自定义相机自定义View
public class AutoFitTextureView extends TextureView {
private int mRatioWidth = 0;
private int mRatioHeight = 0;
public AutoFitTextureView(Context context) {
this(context, null);
}
public AutoFitTextureView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public AutoFitTextureView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public void setAspectRatio(int width, int height) {
if (width < 0 || height < 0) {
throw new IllegalArgumentException("Size cannot be negative.");
}
mRatioWidth = width;
评论5