当给定尺寸比时,在预览视图上画圆不准确

draw circle on preview view is not accurate when dimension ratio is given

我正在尝试通过 setOnTouchListenerpreviewView 上画一个圆,如下所示

        val shape = GradientDrawable()
            shape.shape = GradientDrawable.OVAL
            shape.setColor(Color.TRANSPARENT)
            shape.setStroke(5, Color.WHITE)

        var circleSize = 200

        var img: ImageView = ImageView(this)
            img.background = shape
            val params = FrameLayout.LayoutParams(circleSize, circleSize)
            params.leftMargin = (event.x - (circleSize / 2)).toInt()
            params.topMargin = (event.y - (circleSize / 2)).toInt()
            idFocusIndicator.removeAllViews()
            idFocusIndicator.addView(img, params)

这是我的 PreviewView

<androidx.camera.view.PreviewView
        android:id="@+id/viewFinder"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"

    --->app:layout_constraintDimensionRatio="" // 3:4, 9:16, 1:1 etc

        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/idFocusIndicator"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/transparent"
        app:layout_constraintBottom_toTopOf="@+id/viewFinder"
        app:layout_constraintEnd_toEndOf="@+id/viewFinder"
        app:layout_constraintStart_toStartOf="@+id/viewFinder"
        app:layout_constraintTop_toTopOf="@+id/viewFinder" />

当我点击视图时 constraintDimensionRatio 为空白,即 ""。无论我点击视图的哪个位置,都会以该点为中心出现一个圆圈。

但是当 constraintDimensionRatio 被赋予诸如“3:4”、“1:1”等值时。圆被绘制得离我点击视图的地方不远了。并且对于不同的尺寸比例,它与实际位置的距离是不同的。

当比率为 "3:4" 时,看看我点击的位置和绘制圆圈的位置,当比率为 ""

时不会出现问题

如何解决这个问题?

编辑:

我发现因为 FrameLayout 是用 match_parent 约束值硬编码的,所以它的行为就像那样。所以,如果我创建一个 FrameLayout 并向其添加 ImageView,然后将 FrameLayout 作为子项添加到 parent layout 将解决问题。但我不知道该怎么做!有帮助吗?

没有人回答我的问题所以,我只回答

我通过更改与 PreviewView 完全匹配的约束来解决它。但是,花了将近一天的时间才弄清楚这一点。它可能会帮助犯同样错误的人。

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/idFocusIndicator"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="@android:color/transparent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintDimensionRatio="3:4"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />