cameraX TextureView 预览高度在真实设备中被拉伸

cameraX TextureView preview height is stretched in real device

我正在尝试取消 cameraX TextureView 显示的预览高度。

PreviewConfig previewConfig = new PreviewConfig.Builder()
                .setTargetRotation(getWindowManager().getDefaultDisplay().getRotation())
                .setTargetResolution(new Size(1280, 720))
                .build();

        Preview preview = new Preview(previewConfig);
 <TextureView
        android:id="@+id/view_finder"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

如上所述,我的配置非常简单。

无论我设置什么分辨率,它都无法正常工作。

谁能告诉我如何解决这个问题

看看这张图片瓶子是如何收缩的。

但我得到的输出是正确的。只有预览是这样的

您可以参考这里进行更多定制 https://github.com/android/camera-samples/blob/master/CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/fragments/CameraFragment.kt

一步步复制粘贴这些东西

声明两个常量

private double RATIO_4_3_VALUE = 4.0 / 3.0;
private double RATIO_16_9_VALUE = 16.0 / 9.0;

创建一种根据移动设备选择纵横比的方法

public AspectRatio aspectRatio(int width, int height) {

        double previewRatio = Double.valueOf(Math.max(width, height)) / Math.min(width, height);
        if (Math.abs(previewRatio - RATIO_4_3_VALUE) <= Math.abs(previewRatio - RATIO_16_9_VALUE)) {
            return AspectRatio.RATIO_4_3;
        }
        return AspectRatio.RATIO_16_9;
    }

在 startCamera 方法中以完全相同的方式放置它

private void startCamera() {

        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        final DisplayMetrics displayMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(displayMetrics);
        int height = displayMetrics.heightPixels;
        int width = displayMetrics.widthPixels;


        AspectRatio screenAspectRatio = aspectRatio(width, height);
        PreviewConfig previewConfig = new PreviewConfig.Builder()
                .setTargetRotation(getWindowManager().getDefaultDisplay().getRotation())
                .setTargetAspectRatio(screenAspectRatio)
                .build();


        Preview preview = new Preview(previewConfig);

这将 100% 有效

viewFinder.setScaleType(PreviewView.ScaleType.FIT_CENTER);