3

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.

Cozzamara
  • 1,318
  • 1
  • 14
  • 22

2 Answers2

6

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);
samgak
  • 23,944
  • 4
  • 60
  • 82
  • `.setColorFilter(new PorterDuffColorFilter(Color.WHITE, PorterDuff.Mode.ADD))` – CrandellWS Sep 23 '18 at 03:37
  • I needed the opposit effect, change the white, keep the other colors. This answer helped, but had to try out every possible value, but finally found: PorterDuff.Mode.MULTIPLY – Gavriel Dec 31 '18 at 00:56
-3

This tutorial may be helpful. According to this one, you can replace the white color portion of an image with desired color.

Changing color of drawable icon programmatically http://takeoffandroid.com/uncategorized/changing-color-of-drawable-icon-programmatically/

Harish Sridharan
  • 1,070
  • 6
  • 10