如何使用CameraX和ViewModel
时间: 2024-09-10 12:06:03 浏览: 69
CameraX是Android Jetpack的一部分,它提供了一个易用、可测试且可扩展的相机应用接口,使得开发者能够更容易地使用Android的相机功能。而ViewModel是Jetpack的另一个组件,它主要用于管理UI相关数据,并且在配置更改(如屏幕旋转)时能够保持数据不丢失。以下是使用CameraX和ViewModel的一个基本示例:
1. 首先,在项目的`build.gradle`文件中添加CameraX依赖项:
```gradle
dependencies {
// CameraX核心库
implementation "androidx.camera:camera-camera2:1.0.0"
// CameraX生命周期库
implementation "androidx.camera:camera-lifecycle:1.0.0"
// CameraX视图库
implementation "androidx.camera:camera-view:1.0.0-alpha15"
}
```
2. 在ViewModel中管理CameraX的状态和数据。例如,创建一个ViewModel来存储相机相关的参数和状态:
```kotlin
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.camera.view.PreviewView
import androidx.camera.core.Camera
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import kotlinx.coroutines.launch
class CameraViewModel : ViewModel() {
private val _camera: MutableLiveData<Camera> = MutableLiveData()
val camera: LiveData<Camera> = _camera
fun startCamera(previewView: PreviewView) {
val cameraProviderFuture = ProcessCameraProvider.getInstance(previewView.context)
cameraProviderFuture.addListener(Runnable {
val cameraProvider = cameraProviderFuture.get()
bindPreview(cameraProvider, previewView)
}, ContextCompat.getMainExecutor(previewView.context))
}
private fun bindPreview(cameraProvider: ProcessCameraProvider, previewView: PreviewView) {
val preview = Preview.Builder().build().also {
it.setSurfaceProvider(previewView.createSurfaceProvider())
}
val cameraSelector = CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build()
val imageAnalysis = ImageAnalysis.Builder()
.build()
.also {
// 可以在这里添加分析器,例如用于图像处理或机器学习的代码
}
try {
cameraProvider.unbindAll()
cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis, _camera)
} catch (e: Exception) {
// 处理错误,例如相机正在使用或错误绑定
}
}
}
```
3. 在Activity或Fragment中使用CameraViewModel来启动相机预览。首先创建ViewModel实例,然后在视图准备好之后(例如在Activity的`onCreate()`方法或者Fragment的`onViewCreated()`方法中),调用ViewModel的`startCamera()`方法。
```kotlin
class CameraActivity : AppCompatActivity() {
private lateinit var cameraPreview: PreviewView
private lateinit var cameraViewModel: CameraViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camera)
cameraPreview = findViewById(R.id.camera_preview)
cameraViewModel = ViewModelProvider(this).get(CameraViewModel::class.java)
cameraViewModel.startCamera(cameraPreview)
}
}
```
阅读全文