Jetpack之CameraX的使用

来自:网络
时间:2022-12-26
阅读:
目录

引入依赖

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

首先引入依赖

    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权限哦。

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

返回顶部
顶部