Android Jetpack架构组件(三)CameraX使用入门

Android中使用相机从来就不是一件容易的事。Camera1要自己管理Camera相机实例,要处理SufraceView相关的一堆东西,还有预览尺寸跟画面尺寸的选择,页面生命周期切换等等问题

后来推出了Camera2,从官方Demo 就上千行代码来看,Camera2并不解决用起来复杂的问题,它提供了更多的调用接口,可定制性更好,结果就是对普通开发者来说更加难用

终于Google也意识到这个问题,推出了最终版CameraXCameraX实际上还是用的Camera2,但它对调用API进行了很好的封装,使用起来非常方便。官方教程也很详细:https://codelabs.developers.google.com/codelabs/camerax-getting-started/#0

参考:
https://developer.android.google.cn/training/camerax
https://codelabs.developers.google.com/codelabs/camerax-getting-started/#0

注意:CameraXCamera2一样最低支持API 21,也就是5.0及以上

导入依赖

在app的build.gradle中加入

dependencies {
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

    // Use the most recent version of CameraX, currently that is alpha04
    def camerax_core_version = "1.0.0-beta03"
    def camerax_version = "1.0.0-alpha10"
    implementation "androidx.camera:camera-core:${camerax_core_version}"
    implementation "androidx.camera:camera-camera2:${camerax_core_version}"
    // If you want to use the CameraX View class
    implementation "androidx.camera:camera-view:${camerax_version}"
    // If you want to use the CameraX Extensions library
    implementation "androidx.camera:camera-extensions:${camerax_version}"
    // If you want to use the CameraX Lifecycle library
    implementation "androidx.camera:camera-lifecycle:${camerax_version}"
}

CameraX需要一些Java 8的方法,app的build.gradle的buildTypes之后添加以下内容:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

布局文件和权限

放一个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"
    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"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        />

</androidx.constraintlayout.widget.ConstraintLayout>

权在AndroidManifest.xml中加入相机权限

<uses-permission android:name="android.permission.CAMERA" />

并加入动态申请权限代码,此处省略

启动相机

private void startCamera() {
    executor = ContextCompat.getMainExecutor(this);
    cameraProviderFuture = ProcessCameraProvider.getInstance(this);
    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();
        }
    }, executor);
}

private void bindPreview(ProcessCameraProvider cameraProvider) {
    Preview preview = new Preview.Builder()
            .setTargetAspectRatio(AspectRatio.RATIO_16_9)
            .setTargetRotation(mBinding.previewView.getDisplay().getRotation())
            .build();

    //preview.setSurfaceProvider(mBinding.previewView.getPreviewSurfaceProvider());

    // 相机选择器
    CameraSelector cameraSelector = new CameraSelector.Builder()
            .requireLensFacing(CameraSelector.LENS_FACING_BACK)
            .build();

    // 构建图像捕获用例
    ImageCapture imageCapture = new ImageCapture.Builder()
            .setFlashMode(ImageCapture.FLASH_MODE_AUTO)
            .setTargetAspectRatio(AspectRatio.RATIO_4_3)
            .setCaptureMode(ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY)
            .build();

    // 图像分析
    ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
            // 分辨率
            .setTargetResolution(new Size(1280, 720))
            // 非阻塞模式
            .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
            .build();

//    Camera camera = cameraProvider.bindToLifecycle(this,
//            cameraSelector, imageCapture, imageAnalysis, preview);
    Camera camera = cameraProvider.bindToLifecycle(this,
            CameraSelector.DEFAULT_BACK_CAMERA, preview);

    CameraInfo cameraInfo = camera.getCameraInfo();

    preview.setSurfaceProvider(mBinding.previewView.createSurfaceProvider(cameraInfo));
}

版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/03/25/android-jetpack-architecture-components-getting-started-with-camerax/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
海报
Android Jetpack架构组件(三)CameraX使用入门
Android中使用相机从来就不是一件容易的事。Camera1要自己管理Camera相机实例,要处理SufraceView相关的一堆东西,还有预览尺寸跟画面尺寸的选择,页面生命周……
<<上一篇
下一篇>>
文章目录
关闭
目 录