- 添加依赖
def camerax_version = "1.0.0"
// CameraX core library using camera2 implementation
implementation "androidx.camera:camera-camera2:$camerax_version"
// CameraX Lifecycle Library
implementation "androidx.camera:camera-lifecycle:$camerax_version"
// CameraX View class
implementation "androidx.camera:camera-view:1.0.0-alpha24"
- 创建预览previewView布局
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.camera.view.PreviewView
android:id="@+id/viewFinder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
- 申请相机权限:
manifest中添加:
<uses-feature android:name="android.hardware.camera.any" />
<uses-permission android:name="android.permission.CAMERA" />
fragment或activity中使用registerforactivityresult
- 请求cameraProvider:
import androidx.camera.lifecycle.ProcessCameraProvider
import com.google.common.util.concurrent.ListenableFuture
class MainActivity : AppCompatActivity() {
private lateinit var cameraProviderFuture : ListenableFuture<ProcessCameraProvider>//定义一个字段
override fun onCreate(savedInstanceState: Bundle?) {
startCamera()
}
private fun startCamera(){
cameraProviderFuture = ProcessCameraProvider.getInstance(this)
}
}
- 剩余的配置
private fun startCamera() {
cameraProviderFuture = ProcessCameraProvider.getInstance(requireContext())//创建 ProcessCameraProvider 的实例。这用于将相机的生命周期绑定到生命周期所有者。这消除了打开和关闭相机的任务,因为 CameraX 具有生命周期感知能力。
cameraProviderFuture.addListener(Runnable {//----------1
val cameraProvider = cameraProviderFuture.get()//用来把相机的生命周期绑定到fragment
bindPreview(cameraProvider)
}, ContextCompat.getMainExecutor(requireContext()))
}
private fun bindPreview(cameraProvider : ProcessCameraProvider) {
val preview : Preview = Preview.Builder()//构建preview-----------------2
.build().also {
it.setSurfaceProvider(previewView.surfaceProvider)//和androidx.camera.view.PreviewView控件绑定
}
val cameraSelector : CameraSelector = CameraSelector.Builder()//选择前后相机----------------3
.requireLensFacing(CameraSelector.LENS_FACING_BACK)//可选择前相机或后相机
.build()
var camera = cameraProvider.bindToLifecycle(this as LifecycleOwner, cameraSelector, preview)//把相机的生命周期绑定到fragment---------4
//目前只有preview这一个usecase
}