【问题标题】:How to set color code from colors.xml in a vector drawable?如何在矢量可绘制对象中从 colors.xml 设置颜色代码?
【发布时间】:2016-09-28 11:19:25
【问题描述】:

我想在 res 文件夹的 colors.xml 文件中设置矢量 drawable 中的颜色代码。

【问题讨论】:

    标签: android android-drawable android-vectordrawable


    【解决方案1】:

    你可以简单地使用

    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>
    

    【讨论】:

      【解决方案2】:

      以编程方式,

      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,因为有时它们不适用于低端设备。

      【讨论】:

      • 在 XML android:src 中这有效,但如果您尝试将 android:fillColor="@color/your_color" 放入 VectorDrawable 并在 ContextCompat.getDrawable(context, drawableRes) 表达式中使用它,则无效。它仍然在 Android 10 上崩溃。也许根本不支持此功能?
      【解决方案3】:

      您需要使用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"/>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多