温馨提示×

如何在App中集成Android PreviewView

小樊
95
2024-08-02 03:47:14
栏目: 编程语言

要在App中集成Android PreviewView,您需要按照以下步骤操作:

  1. 在您的App的build.gradle文件中添加相应的依赖:
implementation 'androidx.camera:camera-camera2:1.0.0-beta01'
implementation 'androidx.camera:camera-lifecycle:1.0.0-beta01'
  1. 在您的布局文件中添加PreviewView:
<androidx.camera.view.PreviewView
    android:id="@+id/previewView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
  1. 在您的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))
}
  1. 运行您的App并查看摄像头预览在PreviewView中显示的效果。

通过以上步骤,您可以在您的App中成功集成Android PreviewView。

0