要在App中集成Android PreviewView,您需要按照以下步骤操作:
- 在您的App的build.gradle文件中添加相应的依赖:
implementation 'androidx.camera:camera-camera2:1.0.0-beta01' implementation 'androidx.camera:camera-lifecycle:1.0.0-beta01'
- 在您的布局文件中添加PreviewView:
- 在您的Activity或Fragment中初始化PreviewView并启动相机预览:
private lateinit var previewView: PreviewView
private lateinit var cameraProvider: ProcessCameraProvider
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
previewView = findViewById(R.id.previewView)
val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
cameraProviderFuture.addListener({
cameraProvider = cameraProviderFuture.get()
val preview = Preview.Builder().build()
preview.setSurfaceProvider(previewView.surfaceProvider)
val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
cameraProvider.bindToLifecycle(this, cameraSelector, preview)
}, ContextCompat.getMainExecutor(this))
}
- 运行您的App并查看摄像头预览在PreviewView中显示的效果。
通过以上步骤,您可以在您的App中成功集成Android PreviewView。