Dynamically change svg image color in android

I know that using a third-party library, you can use the SVG image in Android. Library like: svg-android

The code for uploading an SVG image is as follows:

public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Create a new ImageView ImageView imageView = new ImageView(this); // Set the background color to white imageView.setBackgroundColor(Color.WHITE); // Parse the SVG file from the resource SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.android); // Get a drawable from the parsed SVG and set it as the drawable for the ImageView imageView.setImageDrawable(svg.createPictureDrawable()); // Set the ImageView as the content view for the Activity setContentView(imageView); } 

Works fine. I can see the image. But now I want to change the color of the SVG image at runtime. To do this, I tried the code below, as indicated in the same project description.

  // 0xFF9FBF3B is the hex code for the existing Android green, 0xFF1756c9 is the new blue color SVG svg = SVGParser.getSVGFromResource(getResources(), R.raw.android, 0xFF9FBF3B, 0xFF1756c9); 

But with this I can not see the changes in color. Therefore, I would like to know how to dynamically change color in a Java file.

+9
android svg android-view imageview svg-filters
source share
3 answers

I have a problem. The problem is the color code that I use in the svg file. Its not really 0xFF9FBF3B but # 9FBF3B
But during java code you have to write it with an ARGB value (for example, 0xFF9FBF3B). I updated it, and now its work is beautiful. I can change the color of the svg file with the same code.

Hopefully this will also help others identify the actual case when the color of the SVG image changes at runtime.

+9
source share

I know this a bit later, but I also had this problem, and I was able to fix this problem using setColorFilter (int color, PorterDuff.Mode mode) .

Example:

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

Using @Antlip Dev answer 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) 

Using:

 your_image.setSvgColor(ContextCompat.getColor(context!!, R.color.gray)) your_image.setSvgColor(context!!, R.color.gray) 
0
source share

All Articles