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

众所周知,矢量图可以作为一个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"-->
相关推荐
传奇开心果编程4 分钟前
【Jetpack Compose娓娓道来】第44课:持久化——让数据“关掉App也不丢”
android·kotlin·移动开发·数据持久化·jetpack compose·ui框架·声明式ui
星空孤辰25 分钟前
【camera 008】android camera id 注册、状态监控等状态变化 全流程梳理
android·windows
恋猫de小郭2 小时前
iOS for Web ,把原生 iOS App 跑到进浏览器里面,倒反天罡
android·前端·ios
思想觉悟3 小时前
Android启动流程之点rc文件
android·linux·面试
_祝你今天愉快13 小时前
Android 高级绘制:[四] Canvas-实际案例操作
android
三少爷的鞋14 小时前
Android 工程师的技术信仰崩塌史
android
AirDroid_cn16 小时前
Android 15 权限回溯:已授予的麦克风权限如何批量回收?
android
Mr_万能胶17 小时前
官方发布,不烧心的 AOSP 编译提速技巧
android·ci/cd·架构
booboosui17 小时前
安卓 8.1 也能装了:代价是一条黄字和两个静默 bug
android
Ehtan_Zheng20 小时前
Jetpack AppState Transform:让 Compose 的响应式状态走出 UI 层
android