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));
}
上一篇 Android Jetpack架构组件(二)Lifecycle使用
下一篇 Android Jetpack架构组件(四)CameraX基本功能
目录
文章列表
1 Grafana插件扩展之Clock安装
Grafana插件扩展之Clock安装
2
设计模式(1)面向对象的六大原则
设计模式(1)面向对象的六大原则
3
Vue解析Markdown实现
Vue解析Markdown实现
4
Fidder设置显式IP地址
Fidder设置显式IP地址
5
Flutter列表侧滑菜单组件实现
Flutter列表侧滑菜单组件实现
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。