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

众所周知,矢量图可以作为一个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"-->
相关推荐
sun0077003 小时前
Android设备推送traceroute命令
android
来来走走3 小时前
Android开发(Kotlin) 高阶函数、内联函数
android·开发语言·kotlin
2501_915921434 小时前
Fastlane 结合 开心上架(Appuploader)命令行版本实现跨平台上传发布 iOS App 免 Mac 自动化上架实战全解析
android·macos·ios·小程序·uni-app·自动化·iphone
雨白4 小时前
重识 Java IO、NIO 与 OkIO
android·java
啦啦9117145 小时前
Niagara Launcher 全新Android桌面启动器!给手机换个门面!
android·智能手机
游戏开发爱好者85 小时前
iOS 上架要求全解析,App Store 审核标准、开发者准备事项与开心上架(Appuploader)跨平台免 Mac 实战指南
android·macos·ios·小程序·uni-app·iphone·webview
xrkhy5 小时前
canal1.1.8+mysql8.0+jdk17+redis的使用
android·redis·adb
00后程序员张6 小时前
混淆 iOS 类名与变量名的实战指南,多工具组合把混淆做成工程能力(混淆 iOS 类名变量名/IPA 成品混淆Ipa/Guard CLI 实操)
android·ios·小程序·https·uni-app·iphone·webview
介一安全7 小时前
【Frida Android】实战篇1:环境准备
android·网络安全·逆向·frida
许愿OvO7 小时前
MySQL触发器
android·mysql·adb