Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change SVG image color in android

Tags:

I know that using third party library, it is possible to use SVG image in Android. Library like: svg-android

The code to load SVG image is like below:

 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); } 

It's working fine. I'm able to see the image. But now I want to change the color for the svg image at runtime. For that I tried the code below as mentioned 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 that I am not able to see the change in the color. So I would like to know how it is possible to change the color dynamically in Java file.

like image 810
Shreyash Mahajan Avatar asked Oct 29 '14 09:10

Shreyash Mahajan


People also ask

How to change color of SVG image in Android?

Make sure this color 0xFF9FBF3B exists in your svg (just open it in a text editor and search for this value). Keep in mind that the color change only happens when you load the file, not dynamically. So, just reload the file to apply the color change.

Can SVG file change color?

Scalable Vector Graphics or SVG's are graphics that are defined using an XML text file. This means they can be opened with a text editor and the HEX code that determines the colors can be changed.


2 Answers

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); 
like image 131
Antlip Dev Avatar answered Oct 22 '22 00:10

Antlip Dev


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.

like image 24
Shreyash Mahajan Avatar answered Oct 22 '22 00:10

Shreyash Mahajan