如何在矢量绘图中设置 colors.xml 的颜色代码?

How to set color code from colors.xml in a vector drawable?

我想在来自 res 文件夹的 colors.xml 文件的可绘制矢量中设置颜色代码。

您需要使用 android:tint="@color/some_color" 来填充矢量图上的颜色

假设您有一个 ImageView 想要使用向量的地方,您可以做类似的事情

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/bg_vector"
    android:tint="@color/some_color"/>

您可以简单地使用

android:fillColor="@color/colorRated"

但它可能不适用于某些低android版本的设备。这就是为什么我通常使用直接 xml 颜色。

android:fillColor="#9ec8e6"

所以,最后看起来像:

<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:width="48dp"
    android:height="48dp">
    <path
        android:pathData="M23.7 12A11.7 11.7 0 0 1 12 23.7 11.7 11.7 0 0 1 0.30000019 12 11.7 11.7 0 0 1 12 0.30000019 11.7 11.7 0 0 1 23.7 12Z"
        android:fillColor="#9ec8e6" />
</vector>

在编程上,

DrawableCompat.setTint(myImageView.getDrawable(), ContextCompat.getColor(context, R.color.your_color));

或通过 xml 使用 fillColor

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportHeight="24"
    android:viewportWidth="24">
<path
    android:fillColor="@color/your_color"
    android:pathData="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z" />

注意: 使用硬编码颜色(即 #000)而不是 @color/your_color,因为有时它们在低端设备上不起作用。