如何使用 CameraX 将 PreviewView 纵横比与捕获的图像相匹配

bal*_*ekg 3 android kotlin android-camera2 android-camerax

我有一个PreviewView占据整个屏幕但工具栏除外。相机的预览效果很好,但是当我拍摄图像时,纵横比完全不同。

我想在成功捕获后向用户显示图像,因此它的大小与 相同,PreviewView因此我不必裁剪或拉伸它。

是否可以在每个设备上更改纵横比,它是它的大小PreviewView还是我必须将其设置为固定值?

Hus*_*eem 10

您可以在构建它们时设置用例PreviewImageCapture用例的纵横比。如果您为两个用例设置相同的纵横比,您应该最终获得与相机预览输出匹配的捕获图像。

示例:将PreviewImageCapture的纵横比设置为 4:3

Preview preview = new Preview.Builder()
            .setTargetAspectRatio(AspectRatio.RATIO_4_3)
            .build();
ImageCapture imageCapture = new ImageCapture.Builder()
            .setTargetAspectRatio(AspectRatio.RATIO_4_3)
            .build();
Run Code Online (Sandbox Code Playgroud)

通过这样做,您很可能最终仍会得到与PreviewView显示内容不匹配的捕获图像。假设您不更改 的默认比例类型PreviewView,它将等于ScaleType.FILL_CENTER,这意味着除非相机预览输出的纵横比与 匹配PreviewViewPreviewView否则将裁剪预览的部分(顶部和底部,或右侧和左侧),导致捕获的图像与PreviewView显示的内容不匹配。要解决此问题,您应该将PreviewView的纵横比设置为与PreviewImageCapture用例相同的纵横比。

示例:将PreviewView的纵横比设置为 4:3

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.camera.view.PreviewView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="3:4"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)