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

众所周知,矢量图可以作为一个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"-->
相关推荐
冬奇Lab5 小时前
MediaPlayer 播放器架构:NuPlayer 的 Source/Decoder/Renderer 三驾马车
android·音视频开发·源码阅读
炸炸鱼.6 小时前
Python 操作 MySQL 数据库
android·数据库·python·adb
用户41659673693558 小时前
nextlib 项目架构与深度技术指南 (Architecture & Technical Master Guide)
android
aq55356008 小时前
Laravel10.x重磅升级,新特性一览
android·java·开发语言
Trouvaille ~9 小时前
【MySQL篇】数据类型:存储数据的基础
android·数据库·mysql·adb·字符集·数据类型·基础入门
2401_8858850410 小时前
开发视频短信接口好开发吗?图文视频短信接口对接教程
android·音视频
千码君201611 小时前
kotlin:Jetpack Compose 给APP添加声音(点击音效/背景音乐)
android·开发语言·kotlin·音效·jetpack compose
Fᴏʀ ʏ꯭ᴏ꯭ᴜ꯭.11 小时前
MySQL半同步复制与GTID实战详解
android·mysql·adb
用户416596736935512 小时前
深度解码:记一次视频时间戳(PTS)异常导致的播放故障排查
android
大白菜和MySQL14 小时前
linux系统环境常用命令
android·linux·adb