Apply ColorFilter but keep transparent shadow in PNG file

I apply ColorFilter to Drawable , I wanted to know if it is possible to change the color of drawable, but keep the shadow in it.

Something like that:

enter image description here

If you applied something like:

 view.getBackground().setColorFilter(new PorterDuffColorFilter(itemView.getResources().getColor(R.color.green_500), PorterDuff.Mode.SRC_IN); 

This applies to ColorFilter , but retains the shadow and alpha values.

How can i achieve this?

+6
source share
3 answers

I think you need a thin one. If so, using the ColorFilterGenerator suggested in Understanding the Use of ColorMatrix and ColorMatrixColorFilter to Change the Tint of a Drawing, you just need to do:

 view.getBackground().setColorFilter(ColorFilterGenerator.adjustHue(180)); 

The result is as follows (the hue is rotated 180 degrees):

enter image description here

Note: All credits for this answer should be sent to @Richard Lalancette for his wonderful answer to the question I related

Comment update:

As you need to specify the target color, you can calculate the source and target HSV values โ€‹โ€‹and use the ColorFilterGenerator to change the hue. For instance:

 // Your source color (The RGB color from your original image is 255,85,78) float[] hsvSource = new float[3]; Color.RGBToHSV(255, 85, 78, hsvSource); // The color whose hue you want to achieve (green for example) float[] hsvTarget = new float[3]; Color.RGBToHSV(0, 200, 18, hsvTarget); view.getBackground().setColorFilter(ColorFilterGenerator.adjustHue(hsvTarget[0] - hsvSource[0])); 

Please note that this approach only takes into account the hue values โ€‹โ€‹of the colors for changing it.

Comment update:

@ A wonderful answer by Jared Rummler ( Understanding the use of ColorMatrix and ColorMatrixColorFilter to change the hue of a drawing ) takes your drawable as a parameter, so you don't need to specify the source color:

 view.getBackground().setColorFilter(ColorFilterGenerator.from(view.getBackground()).to(Color.GREEN)); 
+3
source

The right (and probably the only) way to achieve what you want is to split the selection into several layers and use layerDrawable to compose them. At this point, you can have a color layer that you can change (and you donโ€™t even need to use porter duff)

+1
source

I ran into a problem with the transparent part of PNG and DropShadow, this code worked for me.

  // The colorPrimary is color you want to achieve float colorRed = Color.red(colorPrimary) / 255f; float colorGreen = Color.green(colorPrimary) / 255f; float colorBlue = Color.blue(colorPrimary) / 255f; drawable.setColorFilter(new ColorMatrixColorFilter(new ColorMatrix(new float[]{ 1 - colorRed, 0, 0, 0, colorRed * 255, 0, 1 - colorGreen, 0, 0, colorGreen * 255, 0, 0, 1 - colorBlue, 0, colorBlue * 255, 0, 0, 0, Color.alpha(colorPrimary) / 255f, 0, }))); img.setImageDrawable(drawable); 
0
source

Source: https://habr.com/ru/post/1241797/


All Articles