How to darken a given color (int)

I have a function that takes a given color, and I would like it to darken the color (reduce its brightness by 20% or so). I cannot figure out how to do this, given only the color (int). What is the right approach?

public static int returnDarkerColor(int color){ int darkerColor = .... return darkerColor; } 
+14
source share
6 answers

More features for Android:

  public static int manipulateColor(int color, float factor) { int a = Color.alpha(color); int r = Math.round(Color.red(color) * factor); int g = Math.round(Color.green(color) * factor); int b = Math.round(Color.blue(color) * factor); return Color.argb(a, Math.min(r,255), Math.min(g,255), Math.min(b,255)); } 

You want to use a factor less than 1.0f to darken. try 0.8f .

+44
source

There is an even simpler solution that was not mentioned earlier. Android has a ColorUtils class to help you with this: a Kotlin ColorUtils for an extension function.

 inline val @receiver:ColorInt Int.darken @ColorInt get() = ColorUtils.blendARGB(this, Color.BLACK, 0.2f) 

The ColorUtils.blendARGB method takes your color as the first parameter and the second color that you want to mix, in this case black and finally the last parameter is the ratio between your color and the mixed black color.

+16
source

If you want more simply and not exactly, the following may help you.

 public static int returnDarkerColor(int color){ float ratio = 1.0f - 0.2f; int a = (color >> 24) & 0xFF; int r = (int) (((color >> 16) & 0xFF) * ratio); int g = (int) (((color >> 8) & 0xFF) * ratio); int b = (int) ((color & 0xFF) * ratio); return (a << 24) | (r << 16) | (g << 8) | b; } 
+11
source

A simpler solution using HSV, such as RogueBaneling, offers:

Kotlin

 @ColorInt fun darkenColor(@ColorInt color: Int): Int { return Color.HSVToColor(FloatArray(3).apply { Color.colorToHSV(color, this) this[2] *= 0.8f }) } 

Java

 @ColorInt int darkenColor(@ColorInt int color) { float[] hsv = new float[3]; Color.colorToHSV(color, hsv); hsv[2] *= 0.8f; return Color.HSVToColor(hsv); } 

No complex bitwise operations or Math operations are required. Move 0.8f to the argument, if necessary.

+10
source

Convert the color to an HSV array, then reduce the brightness by 20%, then convert the HSV array back to RGB using HSVToColor . Note. The value you want to change in the array will be V value. (ie hsv[2] )

+4
source

Thus, you can choose a percentage of color and thus get a shade darker or lighter

 ' int color = ((ColorDrawable)c2.getBackground()).getColor(); 

// button background color (c2) int colorLighter = -color * 40/100 + color; int colorDarker = + color * 40/100 + color; 'colorlighter gives us a lighter color cast from the button background Colordarker gives us a darker color cast from the button background

0
source

All Articles