4

我正在尝试从旧的 Android 相机 API 切换到新的 CameraX API。我正在为增强现实应用程序使用预览模式,我需要获取一些信息,例如预览使用的相机的视角和大小。

到目前为止,这是我的代码:

PreviewConfig config = new PreviewConfig.Builder()
                .setLensFacing(CameraX.LensFacing.BACK)
                .setTargetResolution(new Size(dsiWidth, dsiHeight))
                .build();
Preview preview = new Preview(config);
preview.setOnPreviewOutputUpdateListener(new Preview.OnPreviewOutputUpdateListener() {
            @Override
            public void onUpdated(Preview.PreviewOutput output) {
                tvCameraView.setSurfaceTexture(output.getSurfaceTexture());
            }
        });
CameraX.bindToLifecycle(this, preview);

到目前为止,这有效。但是,我如何获取有关预览使用的相机的信息?提前非常感谢!

4

1 回答 1

0

当您使用"androidx.camera:camera-camera2:1.0.0-alpha02"依赖项时,您可以查看类Camera2CameraFactory。在那里你可以看到前置和后置摄像头是如何确定的。

    @Override
    public Set<String> getAvailableCameraIds() throws CameraInfoUnavailableException {
        List<String> camerasList = null;
        try {
            camerasList = Arrays.asList(mCameraManager.getCameraIdList());
        } catch (CameraAccessException e) {
            throw new CameraInfoUnavailableException(
                    "Unable to retrieve list of cameras on device.", e);
        }
        // Use a LinkedHashSet to preserve order
        return new LinkedHashSet<>(camerasList);
    }

    @Nullable
    @Override
    public String cameraIdForLensFacing(LensFacing lensFacing)
            throws CameraInfoUnavailableException {
        Set<String> cameraIds = getAvailableCameraIds();

        // Convert to from CameraX enum to Camera2 CameraMetadata
        Integer lensFacingInteger = -1;
        switch (lensFacing) {
            case BACK:
                lensFacingInteger = CameraMetadata.LENS_FACING_BACK;
                break;
            case FRONT:
                lensFacingInteger = CameraMetadata.LENS_FACING_FRONT;
                break;
        }

        for (String cameraId : cameraIds) {
            CameraCharacteristics characteristics = null;
            try {
                characteristics = mCameraManager.getCameraCharacteristics(cameraId);
            } catch (CameraAccessException e) {
                throw new CameraInfoUnavailableException(
                        "Unable to retrieve info for camera with id " + cameraId + ".", e);
            }
            Integer cameraLensFacing = characteristics.get(CameraCharacteristics.LENS_FACING);
            if (cameraLensFacing == null) {
                continue;
            }
            if (cameraLensFacing.equals(lensFacingInteger)) {
                return cameraId;
            }
        }

        return null;
    }

归结为从相机服务中选择与方向匹配的第一个相机。我假设他们将在未来的 camerax 版本中扩展这些 api。

于 2019-06-27T14:16:07.420 回答