Question

I want to have two cars in different colors (let's say red and blue) displayed at the same time for my game and to do so I use the same LayerDrawable (which is set as an image resource to an ImageView) for both cars:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/car_backstuff"/>
    <item android:drawable="@drawable/car_body"/>
    <item android:drawable="@drawable/car_frontstuff"/>
</layer-list>

The problem is that when I want to color a car, I do it like this:

_layerDrawable.getDrawable(1).setColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);_

but when I do that for the second car (i.e with Color.BLUE) BOTH cars become blue !

I knew that this is because it refers the same resource (R.drawable.car_body in that case) but I want to know if there is a way to apply a ColorFilter different for each car like insert another layer on top of the car body and multiply it or something ?

Was it helpful?

Solution

I answer my own question:

The solution is to call mutate() for the LayerDrawable and after that any changes on a Drawable inside it will not be repercuted to the other one which use the same resource, that's magic !

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top