android vector设置颜色,以编程方式更改android中矢量的fillColor

This正是您所需要的.致帖子的作者@emmaguy.我刚刚添加了Support Library 23.4+的完全支持,它使您能够在运行时停止生成png:

// Gradle Plugin 2.0+

android {

defaultConfig {

vectorDrawables.useSupportLibrary = true

}

}

如果在您的Activity或Application的onCreate上设置了这一行:

AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);

您不仅可以将SVG用于srcCompat,还可以将其与其他属性(如drawViewLeft,background等)一起用于TextView,ToggleButton等.如果在选择器上使用它也可以工作.

注意:我修改了代码以使用VectorDrawableCompat.create而不是ResourcesCompat.getDrawable.否则它将无效并抛出org.xmlpull.v1.XmlPullParserException:二进制XML文件行#2:无效的可绘制标记向量.

中等帖子内容:

首先,我们为两种小玩意创建属性,因此我们可以改变它们的颜色:

然后,在VectorDrawable中,设置我们想要动态更改的部分以使用这些属性:

android:fillColor="?attr/bauble_round"

android:pathData="...." />

android:fillColor="?attr/bauble_small"

android:pathData="...." />

...

创建主题并设置要使用的颜色:

#db486e

#22c7f7

#fec758

#f22424

在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);

而已!当您想要更改颜色时,只需设置不同的主题,您的drawable就会更新.

有关完整样本,请参阅GitHub repo.

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Vector 资源是一种矢量图形格式,与传统的位图不同,它是由一系列的矢量图形命令描述的,可以实现无限缩放而不失真,而且占用的空间比位图小得多。在 Android 开发,使用 Vector 资源可以有效地减少应用的安装包大小,提高应用的性能。 要创建一个 Vector 资源,可以按照以下步骤进行操作: 1. 在 res/drawable 目录下创建一个 XML 文件,例如 ic_vector.xml。 2. 在 XML 文件使用 `<vector>` 标签来定义一个 Vector 图形,例如: ```xml <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24.0" android:viewportHeight="24.0"> <path android:fillColor="#FF000000" android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM8.55,15.03l-2.83,-2.83 1.41,-1.41 1.42,1.42 4.24,-4.24 1.41,1.41 -5.65,5.65z"/> </vector> ``` 其,`<vector>` 标签用于定义 Vector 图形的属性,例如宽度、高度和视口大小等;`<path>` 标签用于定义 Vector 图形的路径,例如填充颜色和路径数据等。使用 Vector 图形的具体语法和属性可以参考官方文档。 3. 在布局文件或代码使用 Vector 资源,例如: ```xml <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" app:srcCompat="@drawable/ic_vector" /> ``` ```java ImageView imageView = findViewById(R.id.image_view); Drawable drawable = VectorDrawableCompat.create(getResources(), R.drawable.ic_vector, null); imageView.setImageDrawable(drawable); ``` 需要注意的是,使用 Vector 资源需要在 app/build.gradle 文件添加以下代码,以支持 API 级别 21 及以下的设备: ```groovy android { defaultConfig { vectorDrawables.useSupportLibrary = true } } dependencies { implementation 'com.android.support:appcompat-v7:28.0.0' } ``` 其vectorDrawables.useSupportLibrary = true 表示使用支持库VectorDrawableCompat 类来加载 Vector 资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值