web-dev-qa-db-ja.com

CameraXでフロントカメラに切り替える方法は?

手順に従いました CameraXの設定を取得するには 、そして今、前面カメラボタンを機能させようとしています。

これが私のセットアップコードです:

private lateinit var preview: Preview

private fun startCamera() {

    // Create configuration object for the viewfinder use case
    val previewConfig = PreviewConfig.Builder().apply {
        setLensFacing(CameraX.LensFacing.BACK)
    }.build()

    // Build the viewfinder use case
    preview = Preview(previewConfig)

    // Every time the viewfinder is updated, recompute layout
    preview.setOnPreviewOutputUpdateListener {

        // To update the SurfaceTexture, we have to remove it and re-add it
        val parent = viewFinder.parent as ViewGroup
        parent.removeView(viewFinder)
        parent.addView(viewFinder, 0)

        viewFinder.surfaceTexture = it.surfaceTexture
        updateTransform()
    }

    // Bind use cases to lifecycle
    CameraX.bindToLifecycle(this, preview)
}

ユーザーが「切り替え」ボタンをクリックすると、前面カメラを使用するようにプレビューを再構成してから、プレビューを再初期化します。

private fun initSwitchButton(view: View) {
    switchButton = view.findViewById(R.id.switch_button)
    switchButton.setOnClickListener {
        val previewConfig = PreviewConfig.Builder().apply { setLensFacing(CameraX.LensFacing.FRONT) }.build()
        preview = Preview(previewConfig)
    }
}

ただし、これは前面カメラに切り替わりません。何が欠けていますか?

4
AndyGable
private LensFacing lensFacing = CameraX.LensFacing.BACK;
private ImageCapture imageCapture = null;
private Button switchButton;


@SuppressLint("RestrictedApi")
private void startCamera() {
    bindCameraUseCases();

    // Listener for button used to switch cameras
    switchButton = view.findViewById(R.id.switch_button);
    switchButton.setOnClickListener(v -> {
        lensFacing = lensFacing == LensFacing.FRONT ? LensFacing.BACK : LensFacing.FRONT;
        try {
            // Only bind use cases if we can query a camera with this orientation
            CameraX.getCameraWithLensFacing(lensFacing);
            bindCameraUseCases();
        } catch (CameraInfoUnavailableException e) {
            // Do nothing
        }
    });
}

private void bindCameraUseCases() {
    // Make sure that there are no other use cases bound to CameraX
    CameraX.unbindAll();

    PreviewConfig previewConfig = new PreviewConfig.Builder().
            setLensFacing(lensFacing)
            .build();
    Preview preview = new Preview(previewConfig);

    ImageCaptureConfig imageCaptureConfig = new ImageCaptureConfig.Builder()
            .setLensFacing(lensFacing)
            .build();
    imageCapture = new ImageCapture(imageCaptureConfig);

    // Apply declared configs to CameraX using the same lifecycle owner
    CameraX.bindToLifecycle(this, preview, imageCapture);
}

Javaバージョン

0
Renegade