Android camerax 预览
引入依赖
def camerax_version = "1.2.0-alpha04" implementation "androidx.camera:camera-core:${camerax_version}" implementation "androidx.camera:camera-camera2:${camerax_version}" implementation "androidx.camera:camera-lifecycle:${camerax_version}" implementation "androidx.camera:camera-view:${camerax_version}"
页面添加预览的视图 PreviewView
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ui.SimpleCaneraActivity"> <androidx.camera.view.PreviewView android:layout_width="0dp" android:layout_height="0dp" android:id="@+id/previewView" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
开启相机预览代码
PreviewView previewView = findViewById(R.id.previewView); previewView.setImplementationMode(PreviewView.ImplementationMode.PERFORMANCE); ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this); cameraProviderFuture.addListener(() -> { try { ProcessCameraProvider cameraProvider = cameraProviderFuture.get(); Preview preview = new Preview.Builder() .build(); CameraSelector cameraSelector = new CameraSelector.Builder() // 设置后置摄像头 .requireLensFacing(CameraSelector.LENS_FACING_BACK) .build(); // previewView 页面的显示视图 preview.setSurfaceProvider(previewView.getSurfaceProvider()); // 下面的方法Activity没有实现 LifecycleOwner 不能直接在 Activity 中使用 // 需要在androidx.activity.ComponentActivity及其子类中使用 (AppCompatActivity, FragmentActivity) Camera camera = cameraProvider.bindToLifecycle((LifecycleOwner) this, cameraSelector, preview); } catch (Exception e) { e.printStackTrace(); } }, ContextCompat.getMainExecutor(this));