首页 文章

可绘制资源xml中的Tint VectorDrawable

提问于
浏览
6

我有一个可选择的Button / ImageView的可绘制资源,如下所示:

<selector>
<item android:state_selected="true">
    <layer-list>
        <item>
            <shape android:shape="oval">
                <solid android:color="@color/blue"/>
            </shape>
        </item>
        <item>
            <bitmap
                android:src="@drawable/ic_icon"
                android:tint="@color/white"/>

        </item>
    </layer-list>
</item>
<item>
    <layer-list>
        <item>
            <shape android:shape="oval">
                <solid android:color="@color/background_unselected"/>
            </shape>
        </item>
        <item>
            <bitmap
                android:src="@drawable/ic_icon"
                android:tint="@color/icon_unselected"/>
        </item>
    </layer-list>
</item>

因为我已切换到使用VectorDrawables,上述声明不起作用,因为我无法引用带有 <bitmap> 标记的VectorDrawable . 但据我所知,这是我可以给图标着色的唯一方法 .

我也不能在代码中应用Colorfilter,因为这会使整个drawable而不仅仅是图标 .

有什么建议?

1 回答

  • 2

    您可以将颜色定义为属性并在SVG中引用它们 . 然后可以加载由主题设计的drawable .

    简短的例子:

    attributes.xml

    <declare-styleable name="vectorColors">
        <attr name="primaryColor" format="color" />
        <attr name="secondaryColor" format="color" />
    </declare-styleable>
    

    ic_icon.xml

    <path
        android:fillColor="?attr/primaryColor"
        android:pathData="...." />
    <path
        android:fillColor="?attr/secondaryColor"
        android:pathData="...." />
    

    styles.xml

    <style name="svgColors">
        <item name="primaryColor">@color/someColor</item> 
        <!-- also can use #RRGGBB way -->
        <item name="secondaryColor">#ff0000</item>
    </style>
    

    然后加载你的主题和drawable:

    Resources.Theme theme = getResources().newTheme();
    theme.applyStyle(R.style.svgColors, false);
    VectorDrawableCompat drawable = VectorDrawableCompat.create(getResources(), R.drawable.ic_icon, theme);
    imageView.setImageDrawable(drawable);
    

    在您的特定选择器中,您应该替换

    <item>
        <bitmap
            android:src="@drawable/ic_icon"
            android:tint="@color/white"/>
    </item>
    

    by <item android:drawable="@drawable/ic_icon">

    Reference and full example

相关问题