前言
一个Jetpack库,提供了一个一致且易于使用的 API,该 API 适用于绝大多数 Android 设备,并向后兼容 Android 5.0
提示:以下是本篇文章正文内容,下面案例可供参考
注意
CameraX 具有以下最低版本要求:
- Android API 级别 21
- Android 架构组件 1.1.1
对于能够感知生命周期的 Activity,请使用 FragmentActivity 或 AppCompatActivity
一、主要优势
1.广泛的设备兼容性——覆盖现有 Android 设备的 98% 以上
2.易用性——主打一个易用性
3.确保各设备间的一致性——不用考虑宽高比、屏幕方向、旋转角度、预览大小和图像大小
4.相机扩展——CameraX 有一个可选的 Extensions API,您只需两行代码,便可借助该 API 实现与设备的原生相机应用相同的特性和功能
二、CameraX的结构介绍
借助名为“用例”的抽象概念与设备的相机进行交互。提供的用例如下:
- 预览:接受用于显示的surface 例如 PreviewView
- 图片分析:为分析(例如机器学习)提供CPU可访问的缓冲区
- 图片拍摄:拍摄并保存图片
- 视频拍摄:通过VideoCapture拍摄 视频 或 音频
三、声明依赖项
以下内容添加到应用的每个模块的 build.gradle
文件中:
dependencies {
// CameraX core library using the camera2 implementation
val camerax_version = "1.3.0-alpha07"
// The following line is optional, as the core library is included indirectly by camera-camera2
implementation("androidx.camera:camera-core:${camerax_version}")
implementation("androidx.camera:camera-camera2:${camerax_version}")
// If you want to additionally use the CameraX Lifecycle library
implementation("androidx.camera:camera-lifecycle:${camerax_version}")
// If you want to additionally use the CameraX VideoCapture library
implementation("androidx.camera:camera-video:${camerax_version}")
// If you want to additionally use the CameraX View class
implementation("androidx.camera:camera-view:${camerax_version}")
// If you want to additionally add CameraX ML Kit Vision Integration
implementation("androidx.camera:camera-mlkit-vision:${camerax_version}")
// If you want to additionally use the CameraX Extensions library
implementation("androidx.camera:camera-extensions:${camerax_version}")
}
清单文件中注册权限,应用需要 CAMERA 权限。如需将图片保存到文件中,除非所用设备搭载 Android 10 或更高版本,否则应用还需要 WRITE_EXTERNAL_STORAGE 权限。
<!-- Enable instant app support -->
<dist:module dist:instant="true" />
<!-- Declare features -->
<uses-feature android:name="android.hardware.camera" />
<!-- Declare permissions -->
<uses-permission android:name="android.permission.CAMERA" />