Dynamically change SVG image color in android

Shreyash Mahajan picture Shreyash Mahajan · Oct 29, 2014 · Viewed 26.3k times · Source

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.

Answer

Antlip Dev picture Antlip Dev · Oct 16, 2015

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