PreviewView是Android Jetpack CameraX庫中用于預覽相機圖像的視圖組件,配合CameraX可以實現相機預覽功能。下面是一個簡單的示例代碼,演示如何使用PreviewView和CameraX配合實現相機預覽:
// 創建預覽用的PreviewView組件
PreviewView previewView = findViewById(R.id.previewView);
// 設置CameraX配置
ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);
// 綁定預覽用例
cameraProviderFuture.addListener(() -> {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
Preview preview = new Preview.Builder().build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
cameraProvider.unbindAll();
cameraProvider.bindToLifecycle(this, cameraSelector, preview);
}, ContextCompat.getMainExecutor(this));
在上面的示例中,我們首先創建了一個PreviewView組件用于顯示相機預覽圖像。然后通過ProcessCameraProvider.getInstance(this)獲取CameraX的實例,設置預覽用例和相機選擇器,最后使用cameraProvider.bindToLifecycle()方法將預覽用例綁定到相機的生命周期中。
需要注意的是,使用CameraX庫需要在build.gradle文件中添加相應的依賴:
dependencies {
def camerax_version = "1.1.0-alpha11"
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:1.0.0-alpha22"
}
以上就是Android PreviewView與CameraX配合實現相機預覽功能的簡單示例。希望能幫助到你。