Search code examples
androidhtmlshapedrawablecolormatrix

Replace single (black) color in ShapeDrawable with another color in Android


Let's say I have an ShapeDrawable in Android. Not a bitmap. I would like to replace single color (stroke color) in it by another color dynamically. The new desired color is not known at design time and can't be put into drawable resource.

For example, go from picture 1 (where black color represents the color I want to replace, and checkered background is the background not covered by the shape outline):

picture 1

to image 2, where red is the color I want:

picture 2

I can build the shape using alpha masks if necessary - i.e. have the white or black colors transparent, if necessary, or make the outline green, for example. The white fill color must remain white in the final result.

Is it possible to achieve that with standard color filters - ColorMatrixColorFilter, or PorterDuffColorFilter ? If so, I'm having hard time figuring out specific filter. I assume custom ColorFilter is not possible.


Solution

  • In the specific case of having a black border that you want to set to an arbitrary color, and a white interior, you can use a PorterDuff filter in ADD mode. Since it's saturating it won't have any effect on the white area, and since black is zero adding the color will effectively set all black areas to that color.

    e.g. to set it to red:

     drawable.setColorFilter(0x00ff0000, PorterDuff.Mode.ADD);