Search code examples
androidsvgandroid-vectordrawable

How to set tint of vectorDrawable without modifying the original drawable?


I am trying to use SVG file in my View class, and the problem I am running into is: When I set the tint color of my VectorDrawable like this:

var d = AppCompatResources.getDrawable(context, R.drawable.icon)
var vDraw = VectorDrawable()
vDraw  = d as VectorDrawable
DrawableCompat.setTint(vDraw , Color.RED)
vDraw.draw(canvas)

I am ending up in modifying the original drawable. Is there a way I can do that in code without modifying the original SVG?


Solution

  • You need to call the drawable mutate() method. From the documentation:

    Make this drawable mutable. This operation cannot be reversed. A mutable drawable is guaranteed to not share its state with any other drawable. This is especially useful when you need to modify properties of drawables loaded from resources. By default, all drawables instances loaded from the same resource share a common state; if you modify the state of one instance, all the other instances will receive the same modification. Calling this method on a mutable Drawable will have no effect.

    And since you want to tint your drawable, you need to use also the DrawableCompat.wrap(drawable). This will allow:

    Potentially wrap {@code drawable} so that it may be used for tinting across the different API levels, via the tinting methods in this class.

    Applying this to your code:

    var drawable = AppCompatResources.getDrawable(context, R.drawable.icon)
    drawable = drawable.mutate();
    drawable = DrawableCompat.wrap(drawable);
    DrawableCompat.setTint(drawable , Color.RED)
    drawable.draw(canvas)