缩放 ImageView 并保持边距

Scale ImageView and keep margins

我正在制作一个应用程序并希望图像能够在不同尺寸的屏幕上很好地缩放,但是当我使宽度和高度与父级匹配时,它忽略了边距,使图像越界越小设备和较大的设备太小。我找到的修复在下面的答案中:

我喜欢将图像四舍五入,所以我将它们放在 CardView 中。它看起来像这样:

<androidx.cardview.widget.CardView
            android:id="@+id/cardView"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintDimensionRatio="1:1"
            android:adjustViewBounds="true"
            android:layout_marginRight="32dp" <-- your margins
            android:layout_marginLeft="32dp" <-- your margins
            app:cardCornerRadius="20dp" <-- your rounded corners radius
            app:cardBackgroundColor="@color/background" <-- your background color
            app:layout_constraintTop_toBottomOf="@+id/top" <-- the view you have on top of the image. If there's nothing on top, set it to "parent" or skip it altogether.
            app:layout_constraintBottom_toTopOf="@id/bottom" <-- the view you have under the image. If there's nothing on top, set it to "parent" or skip it altogether.
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent">

            <ImageView
                android:id="@+id/imageView"
                android:layout_gravity="center"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:scaleType="centerCrop"
                android:adjustViewBounds="true"
                android:layout_centerHorizontal="true"/>

        </androidx.cardview.widget.CardView>

如果您不喜欢四舍五入的图片,请跳过 CardView:

<ImageView
            android:id="@+id/imageView"
            android:layout_gravity="center"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            app:layout_constraintDimensionRatio="1:1"
            android:adjustViewBounds="true"
            android:layout_marginRight="32dp" <-- your margins
            android:layout_marginLeft="32dp" <-- your margins
            android:scaleType="centerCrop"
            app:layout_constraintTop_toBottomOf="@+id/eachText"<-- the view you have on top of the image. If there's nothing on top, set it to "parent" or skip it altogether.
            app:layout_constraintBottom_toTopOf="@id/bottom" <-- the view you have under the image. If there's nothing on top, set it to "parent" or skip it altogether.
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"/>

您应该将其添加到 xml 文件中的 imageView 中

android:scaleType="fitXY"

如果它不起作用,请更改“fitXY”以保留 scaleType 的选项。