Android - 如何为具有两种或多种颜色的矢量绘图设置色调

Android - how to set tint on vector drawables with two or more colors

我喜欢矢量绘图,而且我可以使用简单的色调属性在每个布局中更改它的色调,如下所示:

<ImageView
            android:id="@+id/image_payment_cash"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:tint="@color/color1"
            android:src="@drawable/ic_cash" />

但我想知道是否有办法为同一个矢量(多色矢量)指定两种或多种色调? 所以它可以这样设置:

 <ImageView
            android:id="@+id/image_payment_cash"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:tint1="@color/color1"
            android:tint2 = "@color/color2"
            android:src="@drawable/ic_cash" />

不,在 XML 中默认情况下无法为 Vector Drawable 着色多种不同颜色。

您可以在 Java/Kotlin 中以编程方式将可绘制文件扩展为 VectorDrawable class,然后遍历每一层,然后单独更改颜色。
通过使用相同的代码,您可以创建具有 "tint1" 和 "tint2" 属性的自定义 ImageView。

如果您在 API 21 以下使用 Vector Drawable,请注意 class 框架使用的不同 classes 来向后移植一些 VD 元素。