This https://medium.com/@emmaguy/dynamically-changing-svg-colours-on-android-b026a99137ad#.6q6zxp1gl正是您所需要的。致谢@emmaguy https://medium.com/@emmaguy,该帖子的作者。我刚刚添加了全力支持支持库 23.4+ https://android-developers.blogspot.com.ar/2016/02/android-support-library-232.html,这使您能够在运行时停止生成 png:
// Gradle Plugin 2.0+
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
如果此行在您的活动或应用程序的 onCreate 上设置:
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
您不仅可以使用 SVGsrcCompat
而且还具有其他属性,例如drawableLeft
, background
等TextView、ToggleButton等。如果用在选择器上它也可以工作。
Note: 我修改了代码来使用VectorDrawableCompat.create
代替ResourcesCompat.getDrawable
。否则它不会工作并抛出org.xmlpull.v1.XmlPullParserException: Binary XML file line #2: invalid drawable tag vector
.
中帖子内容:
首先,我们为两种小玩意创建属性,这样我们就可以改变它们的颜色:
<declare-styleable name="ChristmasTree">
<attr name="bauble_round" format="color" />
<attr name="bauble_small" format="color" />
</declare-styleable>
然后,在 VectorDrawable 中,设置我们想要动态更改的部分以使用这些属性:
<path
android:fillColor="?attr/bauble_round"
android:pathData="...." />
<path
android:fillColor="?attr/bauble_small"
android:pathData="...." />
...
创建主题并设置您要使用的颜色:
<style name="UpdatedScene" parent="DefaultScene">
<item name="bauble_round">#db486e</item>
<item name="bauble_small">#22c7f7</item>
</style>
<style name="DefaultScene">
<item name="bauble_round">#fec758</item>
<item name="bauble_small">#f22424</item>
</style>
在 ImageView 中使用可绘制对象:
final ContextThemeWrapper wrapper = new ContextThemeWrapper(this, R.style.DefaultScene);
final Drawable drawable = VectorDrawableCompat.create(getResources(), R.drawable.christmas, wrapper.getTheme());
imageView.setImageDrawable(drawable);
就是这样!当您想更改颜色时,只需设置不同的主题,您的绘图就会更新。
请参阅 GitHubrepo https://github.com/emmaguy/dynamic-svg-colours以获得完整的样本。