Android

关注公众号 jb51net

关闭
首页 > 软件编程 > Android > Jetpack CameraX

Jetpack之CameraX的使用

作者:幸大叔

CameraX 是Jetpack的一个成员,可以更轻松地开发相机应用,支持搭载Android 5.0及以上设备,具有广泛的设备兼容性,也可确保各设备间的一致性,如宽高比、屏幕方向、旋转角度、预览大小和图像大小等

引入依赖

下面,就使用该库来打造一个简单的相机应用吧~

首先引入依赖

    def camerax_version = "1.1.0-beta03"
    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-video:${camerax_version}"
    implementation "androidx.camera:camera-view:${camerax_version}"
    implementation "androidx.camera:camera-extensions:${camerax_version}"

预览

将 PreviewView 添加到布局中

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <androidx.camera.view.PreviewView
        android:id="@+id/previewView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <Button
        android:id="@+id/take"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:text="拍照" />
</RelativeLayout>

获取 cameraProvider

        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener({
            val cameraProvider = cameraProviderFuture.get()
            bindViewAndLifecycle(cameraProvider)
        }, ContextCompat.getMainExecutor(this))

配置 ImageCapture

    private val imageCapture: ImageCapture by lazy {
        ImageCapture.Builder().build()
    }

bindViewAndLifecycle:绑定视图和Lifecycle

    private fun bindViewAndLifecycle(cameraProvider: ProcessCameraProvider) {
        val previewView = findViewById<PreviewView>(R.id.previewView)
        val cameraSelector = CameraSelector.Builder()
            //如果是前置,可使用CameraSelector.LENS_FACING_FRONT
            .requireLensFacing(CameraSelector.LENS_FACING_BACK)
            .build()
        val preview = Preview.Builder().build()
        preview.setSurfaceProvider(previewView.surfaceProvider)
        cameraProvider.bindToLifecycle(
            this as LifecycleOwner,
            cameraSelector,
            imageCapture,
            preview
        )
    }

这样,就完成了相机的预览功能了。

拍摄

实现拍照功能也很简单,只需要创建文件,然后调用imageCapture的takePicture方法。

    private fun takePicture() {
        val path =
            getExternalFilesDir(null)?.absolutePath + File.separator + System.currentTimeMillis() + ".jpg"
        val photoFile = File(path)
        if (!photoFile.exists()) {
            photoFile.createNewFile()
        }
        val fileOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build()
        imageCapture.takePicture(
            fileOptions,
            ContextCompat.getMainExecutor(this),
            object : ImageCapture.OnImageSavedCallback {
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    Toast.makeText(this@MainActivity, "保存成功", Toast.LENGTH_SHORT).show()
                }
                override fun onError(exception: ImageCaptureException) {
                    Log.e(tag, "onError message:${exception.message}")
                }
            })
    }

点击按钮时调用此方法即可

        findViewById<Button>(R.id.take).setOnClickListener {
            takePicture()
        }

注意:作为相机应用,可别忘了申请CAMERA权限哦。

这样,一个简单的相机应用就完成啦~

到此这篇关于Jetpack之CameraX的使用的文章就介绍到这了,更多相关Jetpack CameraX内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文