dependencies { def camerax_version = "1.0.2" // 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:1.1.0-beta02" // If you want to additionally use the CameraX View class implementation "androidx.camera:camera-view:1.1.0-beta02" // If you want to additionally use the CameraX Extensions library implementation "androidx.camera:camera-extensions:1.1.0-beta02"
cameraProviderFuture.addListener(Runnable { val cameraProvider = cameraProviderFuture.get() bindPreview(cameraProvider)
}, ContextCompat.getMainExecutor(this))
选择相机并绑定生命周期和用例
创建并确认 CameraProvider 后,请执行以下操作:
1、创建 Preview。
2、指定所需的相机 LensFacing 选项。
3、将所选相机和任意用例绑定到生命周期。
4、将 Preview 连接到 PreviewView。
以下代码展示了一个示例:
1 2 3 4 5 6 7 8 9 10 11
privatefunbindPreview(cameraProvider: ProcessCameraProvider?) { var preview: Preview = Preview.Builder() .build()
var cameraSelector: CameraSelector = CameraSelector.Builder() .requireLensFacing(CameraSelector.LENS_FACING_BACK) .build()
preview.setSurfaceProvider(dataBinding.previewView.getSurfaceProvider()) var camera = cameraProvider?.bindToLifecycle(thisas LifecycleOwner, cameraSelector, preview) }
请注意,bindToLifecycle() 会返回一个 Camera 对象。如需详细了解如何控制相机输出(如变焦和曝光),请参阅此指南。