Sas*_* K. 32 android vector android-vectordrawable
我想以编程方式在Android中编辑矢量文件的填充颜色.
在xml文件中,我可以使用android:fillColor属性设置我的颜色, 但我想在运行时更改颜色.
有什么例子吗?谢谢.
sai*_*der 32
这正是您所需要的.学分@emmaguy,该帖子的作者.我刚刚添加了支持库23.4+的完全支持,它使您能够在运行时停止生成png:
// Gradle Plugin 2.0+
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
Run Code Online (Sandbox Code Playgroud)
如果在您的Activity或Application的onCreate上设置了这一行:
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
Run Code Online (Sandbox Code Playgroud)
您可以使用SVGs不仅srcCompat还可以与其他属性,如drawableLeft,background等在TextView的,切换按钮等.如果在选择器上使用它也可以工作.
注意:我修改了代码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>
Run Code Online (Sandbox Code Playgroud)
然后,在VectorDrawable中,设置我们想要动态更改的部分以使用这些属性:
<path
android:fillColor="?attr/bauble_round"
android:pathData="...." />
<path
android:fillColor="?attr/bauble_small"
android:pathData="...." />
...
Run Code Online (Sandbox Code Playgroud)
创建主题并设置要使用的颜色:
<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>
Run Code Online (Sandbox Code Playgroud)
在ImageView中使用drawable:
final ContextThemeWrapper wrapper = new ContextThemeWrapper(this, R.style.DefaultScene);
final Drawable drawable = VectorDrawableCompat.create(getResources(), R.drawable.christmas, wrapper.getTheme());
imageView.setImageDrawable(drawable);
Run Code Online (Sandbox Code Playgroud)
而已!当您想要更改颜色时,只需设置不同的主题,您的drawable就会更新.有关完整样本,请参阅GitHub 仓库.
Alb*_*tNf 16
如果要更改整个颜色,可以应用PorterduffColorFilter.但这对一个人来说不起作用<path>.仅适用于整个绘图.
public void applyThemeToDrawable(Drawable image) {
if (image != null) {
PorterDuffColorFilter porterDuffColorFilter = new PorterDuffColorFilter(Color.BLUE,
PorterDuff.Mode.SRC_ATOP);
image.setColorFilter(porterDuffColorFilter);
}
}
Run Code Online (Sandbox Code Playgroud)
VectorDrawable扩展了Drawable类.见文档
小智 7
将setColorFilter()方法添加到图像内容向量(在api级别8中添加),如下所示:
imgshare = (Imageview) findviewbyId(R.id.imageshare);
imgshare.setColorFilter(color);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
23868 次 |
| 最近记录: |