CameraX Java 1.0.0-alpha10 安卓开发

学习一下CameraX,目前使用的版本是1.0.0-alpha10

def camerax_version = "1.0.0-alpha10"
    implementation "androidx.camera:camera-camera2:${camerax_version}"
    // If you want to use the CameraX View class
    implementation "androidx.camera:camera-view:1.0.0-alpha08"
    // If you want to use the CameraX Extensions library
    implementation "androidx.camera:camera-extensions:1.0.0-alpha08"
    // If you want to use the CameraX Lifecycle library
    implementation "androidx.camera:camera-lifecycle:${camerax_version}"

还有这个也莫忘记了

compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

简单些,直接放代码。我只写了预览功能,如果需要别的功能建议看一下文档或者官方的实例(非java写的,但是结构差不太多,对照着写就好啦)
这里建议下用java的同学,就不用看CameraX稍微早一点的教程了,这东西一版本一个样,说不定过几天我这篇也报废了(@_@;)
早一点的,例如PreviewConfig,textureView都没了,变成了新的东西又加了一堆东西。

public class MainActivity extends AppCompatActivity {
    PreviewView Mpreview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Mpreview = findViewById(R.id.view_finder);

        Mpreview.post(new Runnable() {
            @Override
            public void run() {
                startCamera(MainActivity.this);
            }
        });

    }

   
    private void startCamera(Context context) {
        ListenableFuture cameraProviderFuture = ProcessCameraProvider.getInstance(context);
        cameraProviderFuture.addListener(new Runnable() {
            @Override
            public void run() {
                try {
                    ProcessCameraProvider processCameraProvider= (ProcessCameraProvider) cameraProviderFuture.get();
                    Preview preview = new Preview.Builder()
                            .setTargetAspectRatio(AspectRatio.RATIO_16_9)
                            .setTargetRotation(Mpreview.getDisplay().getRotation())
                            .build();

                    preview.setSurfaceProvider(Mpreview.getPreviewSurfaceProvider());
                    processCameraProvider.bindToLifecycle((LifecycleOwner) context, CameraSelector.DEFAULT_FRONT_CAMERA,preview);
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }, ContextCompat.getMainExecutor(context));
    }
}
<androidx.camera.view.PreviewView
        android:id="@+id/view_finder"
        android:layout_width="match_parent"
        android:layout_height="400dp"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />

相机权限也别忘记啦,能学到这个库的想必也都早就会了,我就不放设置权限的代码了
CameraX Java 1.0.0-alpha10 安卓开发_第1张图片

你可能感兴趣的:(app)