在 ConstraintLayout 中缩放矢量图形

Scaling vector graphics in ConstraintLayout

这是一个 "how-to" 问题。

我有一个 android activity,在 ConstraintLayout 中有 6 个 ImageView 对象。我希望它们水平放置,始终使用屏幕的整个宽度。对于更大的屏幕,而不是 ImageViews 之间的空白,我希望 ImageViews 放大,保持它们的纵横比。图片内容我用的是矢量资源。

如何做到这一点?

ConstraintLayout 内,您可以将您的 ImageView

放在一条链中
app:layout_constraintHorizontal_chainStyle="spread_inside"

app:layout_constraintHorizontal_chainStyle="spread" 

并使每个视图的宽度 0dp 以水平扩展每个视图以匹配其约束。无论是纵向模式还是横向模式,这都会将每个视图分布在屏幕的宽度上。 (参见链的 this discussion。)

完成后,为每个 ImageView 指定 android:adjustViewBounds="true",这将使矢量图像放大以填充其视图。 (参见 here and here)。

下面是两个示例图像和使用的 XML。 (我使用了四张图片,但它也适用于六张。)

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        app:srcCompat="@drawable/ic_android_green_24dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/imageView2"
        app:layout_constraintHorizontal_chainStyle="spread_inside"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="0dp"
        android:adjustViewBounds="true"
        app:srcCompat="@drawable/ic_android_green_24dp"
        app:layout_constraintEnd_toStartOf="@+id/imageView3"
        app:layout_constraintStart_toEndOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="@+id/imageView" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        app:srcCompat="@drawable/ic_android_green_24dp"
        app:layout_constraintEnd_toStartOf="@+id/imageView4"
        app:layout_constraintStart_toEndOf="@+id/imageView2"
        app:layout_constraintTop_toTopOf="@+id/imageView" />

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="0dp"
        android:adjustViewBounds="true"
        app:srcCompat="@drawable/ic_android_green_24dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageView3"
        app:layout_constraintTop_toTopOf="@+id/imageView" />
</android.support.constraint.ConstraintLayout>