官方发布
- Android Developer Document
- Google Demo
- Getting Started with CameraX
- News: Whats new in camerax
- News: Androids camerax jetpack library is now in beta
- Android Jetpack CameraX 库 Beta 版正式发布!
本文
从官方示例 Copy 而来,主要代码来自 Google Demo
的 CameraFragment
开始使用 CameraX
1. 导入依赖
在 app 或 module 的 build.gradle 中添加依赖:
dependencies {
def camerax_version = '1.0.0-beta02'
implementation "androidx.camera:camera-core:$camerax_version"
implementation "androidx.camera:camera-camera2:$camerax_version"
implementation "androidx.camera:camera-lifecycle:$camerax_version"
implementation 'androidx.camera:camera-view:1.0.0-alpha09'
}
配置 Java 版本 8 以上
android {
...
defaultConfig {
// Jetpack 库向前兼容的最低版本 Android L
minSdkVersion 21
...
}
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
2. 添加相机权限
<uses-permission android:name="android.permission.CAMERA" />
3. 添加 PreviewView
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<androidx.camera.view.PreviewView
android:id="@+id/preview_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
4. 请求相机权限(略)
5. 初始化相机,开启预览
- 选择摄像头(前置 or 后置)
private int lensFacing = CameraSelector.LENS_FACING_BACK;
CameraSelector cameraSelector = new CameraSelect