如何在Camera X库中以编程方式更改相机镜头的朝向?

时间:2020-11-06 02:48:40

标签: android android-jetpack android-camerax

当前我正在使用此gradle

implementation "androidx.camera:camera-camera2:1.0.0-beta11"
implementation "androidx.camera:camera-lifecycle:1.0.0-beta11"
implementation "androidx.camera:camera-view:1.0.0-alpha18"

所以我想在用户点击一个按钮后以编程方式改变相机镜头的朝向。这是我尝试使用的代码

class CameraFragment : Fragment() {

    private var cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA

    lateinit var mContext: Context
    lateinit var mActivity: FragmentActivity

    override fun onAttach(context: Context) {
        super.onAttach(context)

        mContext = context
        activity?.let { mActivity = it }

    }

    private fun toggleFrontBackCamera() {


        if (cameraSelector == CameraSelector.DEFAULT_BACK_CAMERA) {
            cameraSelector = CameraSelector.DEFAULT_FRONT_CAMERA
        } else if (cameraSelector == CameraSelector.DEFAULT_FRONT_CAMERA) {
            cameraSelector == CameraSelector.DEFAULT_BACK_CAMERA
        }

        startCamera()


    }

    private fun startCamera() {
        val cameraProviderFuture = ProcessCameraProvider.getInstance(mContext)

        cameraProviderFuture.addListener(Runnable {
            // Used to bind the lifecycle of cameras to the lifecycle owner
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()

            // Preview
            val preview = Preview.Builder()
                    .build()
                    .also {
                        it.setSurfaceProvider(previewView.surfaceProvider)
                    }


            imageCapture = ImageCapture.Builder().build()


            try {
                // Unbind use cases before rebinding
                cameraProvider.unbindAll()

                // Bind use cases to camera
                cameraProvider.bindToLifecycle(
                        this, cameraSelector, preview, imageCapture)

            } catch (exc: Exception) {
                Log.e(TAG, "Use case binding failed", exc)
            }

        }, ContextCompat.getMainExecutor(mContext))
    }


}

我使用toggleFrontBackCamera()方法以编程方式更换镜头。

如您所见,默认摄像头是后置摄像头,然后当用户点击按钮更改摄像头时,将首次调用toggleFrontBackCamera()方法,然后摄像头将从“后退”更改为“前” 。这里没问题

但是问题是,当用户想要从前后到后相机再次更换相机镜头时,toggleFrontBackCamera()将不起作用,它卡在CameraSelector.DEFAULT_FRONT_CAMERA

那么如何以编程方式更改它?

1 个答案:

答案 0 :(得分:2)

在开始时初始化变量:

private var lensFacing = CameraSelector.LENS_FACING_BACK

将您的相机切换方法更改为此:

private fun toggleFrontBackCamera() {
    lensFacing = if (CameraSelector.LENS_FACING_FRONT == lensFacing)
        CameraSelector.LENS_FACING_BACK
    else 
        CameraSelector.LENS_FACING_FRONT
    startCamera()
}

最后在您的CameraSelector中创建一个startCamera()的实例,并在cameraProvider.bindToLifecycle()中使用它:

val cameraSelector = CameraSelector.Builder().requireLensFacing(lensFacing).build()