Dynamically change SVG image color in android

倖福魔咒の 提交于 2019-11-30 09:10:16

I know it's kind of late but I also had this issue and was able to fix this issue using the setColorFilter(int color, PorterDuff.Mode mode) method.

Example:

imageView.setColorFilter(getResources().getColor(android.R.color.black), PorterDuff.Mode.SRC_IN);

I got where is the problem. The issue is with the color code i am using in svg file. Its not exactly 0xFF9FBF3B but #9FBF3B
But during java code you have to write it with ARGB value (e.g. 0xFF9FBF3B). I have updated it and its work fine now. I can able to change the color of svg file with same code.

Hope this will also help others to identify the actual case while changing the color of the SVG image at runtime.

Using the answer of @Antlip Dev in Kotlin.

package com.example.... // Your package.

import android.content.Context
import android.graphics.PorterDuff
import android.support.v4.content.ContextCompat
import android.widget.ImageView

class VectorExt

fun ImageView.setSvgColor(color: Int) =
    this.setColorFilter(color, PorterDuff.Mode.SRC_IN)

fun ImageView.setSvgColor(context: Context, color: Int) =
    this.setColorFilter(ContextCompat.getColor(context, color), PorterDuff.Mode.SRC_IN)

Usage:

your_image.setSvgColor(ContextCompat.getColor(context!!, R.color.gray))
your_image.setSvgColor(context!!, R.color.gray)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!