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

众所周知,矢量图可以作为一个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"-->
相关推荐
奔跑中的蜗牛6661 小时前
一次播放器架构升级:Android 直播间 ANR 下降 60%
android
测试工坊3 小时前
Android 视频播放卡顿检测——帧率之外的第二战场
android
Kapaseker5 小时前
一杯美式深入理解 data class
android·kotlin
鹏多多5 小时前
Flutter使用screenshot进行截屏和截长图以及分享保存的全流程指南
android·前端·flutter
Carson带你学Android5 小时前
OpenClaw移动端要来了?Android官宣AI原生支持App Functions
android
黄林晴5 小时前
Android 删了 XML 预览,现在你必须学 Compose 了
android
三少爷的鞋6 小时前
Android 面试系列 | 内存泄露:从"手动配对"到"架构自愈"
android
恋猫de小郭6 小时前
什么 AI 写 Android 最好用?官方做了一个基准测试排名
android·前端·flutter
louisgeek15 小时前
Android MediatorLiveData
android
锋风1 天前
远程服务器运行Android Studio开发aosp源码
android