安卓 自定义矢量图片控件 - 支持属性修改矢量图路径颜色

众所周知,矢量图可以作为一个drawable文件设置到ImageView里面,但是我常常会碰到同一个矢量图,路径的颜色却老是变化情况,一怒之下写出来这个控件~~

同一个矢量图的文件,设置颜色后:

1.在values下的attrs.xml文件中创建自定义的属性

XML 复制代码
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="vectorImageView">
        <attr name="vectorPathColor" format="color|reference" />
    </declare-styleable>

</resources>

2.创建自定义控件文件 VectorImageView.kt

Kotlin 复制代码
import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.graphics.drawable.DrawableCompat

class VectorImageView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatImageView(context, attrs, defStyleAttr) {

    var iconColor: Int = 0
        set(value) {
            field = value
            if (iconColor != 0) {
                applyIconColor(value)
            }
        }

    init {
        // 初始化时读取自定义属性
        attrs?.let {
            val typedArray = context.obtainStyledAttributes(it, R.styleable.vectorImageView)
            // 使用 getColor 获取颜色,默认值为 0
            iconColor = typedArray.getColor(R.styleable.vectorImageView_vectorPathColor, 0)
            typedArray.recycle()
        }
    }

    // 根据颜色值应用到 ImageView 的矢量图上
    private fun applyIconColor(color: Int) {
        val drawable: Drawable? = drawable

        drawable?.let {
            val wrappedDrawable = DrawableCompat.wrap(it).mutate()
            DrawableCompat.setTint(wrappedDrawable, color)
            setImageDrawable(wrappedDrawable)
        }
    }

3.使用

XML 复制代码
    <包名.VectorImageView
        android:layout_width="@dimen/dp_60"
        android:layout_height="@dimen/dp_60"
        android:src="@drawable/left_arrow"
        app:vectorPathColor="@color/color_A0A5A6" />

<!-- app:vectorPathColor="#FF921D"-->
相关推荐
顾林海36 分钟前
Android ClassLoader加载机制详解
android·面试·源码
用户20187928316736 分钟前
🎨 童话:Android画布王国的奇妙冒险
android
whysqwhw1 小时前
OkHttp框架的全面深入架构分析
android
你过来啊你1 小时前
Android App冷启动流程详解
android
泓博2 小时前
KMP(Kotlin Multiplatform)改造(Android/iOS)老项目
android·ios·kotlin
移动开发者1号2 小时前
使用Baseline Profile提升Android应用启动速度的终极指南
android·kotlin
移动开发者1号2 小时前
解析 Android Doze 模式与唤醒对齐
android·kotlin
菠萝加点糖4 小时前
Kotlin Data包含ByteArray类型
android·开发语言·kotlin
IAM四十二9 天前
Google 端侧 AI 框架 LiteRT 初探
android·深度学习·tensorflow
CYRUS_STUDIO10 天前
手把手教你用 Chrome 断点调试 Frida 脚本,JS 调试不再是黑盒
android·app·逆向