Android 动态设置 SVG 图标颜色 - 轻松实现个性化
要在 Android 中动态设置 SVG 图标的颜色,可以使用 VectorDrawableCompat 类。这个类是在 Support Library 中提供的,用于兼容 Android 5.0 以下的版本。
首先,确保你已经将 SVG 文件转换为 VectorDrawable 格式。可以使用 Android Studio 中的“转换为矢量图”功能来完成这个步骤。
然后,在布局文件中使用 ImageView 来显示 SVG 图标:
<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_svg_icon"/>
接下来,在代码中找到 ImageView 并设置其颜色:
ImageView icon = findViewById(R.id.icon);
Drawable drawable = icon.getDrawable();
if (drawable instanceof VectorDrawableCompat) {
VectorDrawableCompat vectorDrawableCompat = (VectorDrawableCompat) drawable;
vectorDrawableCompat.setTint(ContextCompat.getColor(this, R.color.icon_color));
}
这里,我们首先获取 ImageView 的 Drawable,然后判断它是否为 VectorDrawableCompat 类型。如果是,我们可以将其转换为 VectorDrawableCompat 对象,并使用 setTint() 方法来设置图标的颜色。setTint() 方法接受一个颜色资源作为参数。
最后,记得将 R.color.icon_color 替换为你想要的颜色资源。
原文地址: http://www.cveoy.top/t/topic/dizm 著作权归作者所有。请勿转载和采集!