I can't find out how to use camerax with previewview.
Here is an example of how to use Camerax
with PreviewView
, the code uses the latest versions of CameraX, meaning camera-camera2 version 1.1.0-beta01, and camera-view version 1.1.0-beta01.
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
previewView = view.findViewById(R.id.preview_view);
setCameraProviderListener();
}
private void setCameraProviderListener() {
ListenableFuture<ProcessCameraProvider> cameraProviderFuture =
ProcessCameraProvider.getInstance(requireContext());
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
bindPreview(cameraProvider);
} catch (ExecutionException | InterruptedException e) {
// No errors need to be handled for this Future
// This should never be reached
e.printStackTrace();
}
}, ContextCompat.getMainExecutor(requireContext()));
}
private void bindPreview(ProcessCameraProvider cameraProvider) {
imageAnalyser();
imageCapture();
CameraSelector cameraSelector =
new CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build();
Preview preview = new Preview.Builder().build();
preview.setSurfaceProvider(previewView.getSurfaceProvider());
ViewPort viewPort = previewView.getViewPort();
if (viewPort != null) {
UseCaseGroup useCaseGroup = new UseCaseGroup.Builder()
.addUseCase(preview)
.addUseCase(imageAnalyzer)
.addUseCase(imageCapture)
.setViewPort(viewPort)
.build();
cameraProvider.unbindAll();
Camera camera = cameraProvider.bindToLifecycle(this, cameraSelector, useCaseGroup);
CameraControl cameraControl = camera.getCameraControl();
cameraControl.setLinearZoom((float)0.3);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.camera.view.PreviewView
android:id="@+id/preview_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/Yellow"
android:layout_gravity="center" />
</LinearLayout>
Here is an article that explains PreviewView
and how to use it. It's valid up to version 1.0.0-alpha10 of camera-view, I'll try to keep it up to date.
I had set android:hardwareAccelerated="false"
while debugging a different error, and had forgotten to remove it (or set it to true
). I quickly noticed camera functionality had stopped working.
Make sure there is no android:hardwareAccelerated="false"
in your apps manifest. If there is, either remove it, or set it to true
. If this is set to false
it will affect the camera preview stream.
TL;DR
Remove any android:hardwareAccelerated="false"
in your manifest, or set it true
.
© 2022 - 2024 — McMap. All rights reserved.