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 can't figure out how to do this given just a color (int). What is the proper approach?
public static int returnDarkerColor(int color){
int darkerColor = ....
return darkerColor;
}
A more Android way of doing it:
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 will want to use a factor less than 1.0f
to darken. try 0.8f
.
There's even a simpler solution that has not been mentioned before, Android has a class called ColorUtils
which can you help you with that
here's a Kotlin snippet of an extension function
inline val @receiver:ColorInt Int.darken
@ColorInt
get() = ColorUtils.blendARGB(this, Color.BLACK, 0.2f)
the method ColorUtils.blendARGB
takes your color as the first parameter and the second color you want to blend, black
in this case and finally, the last parameter is the ratio between your color and the black color you're blending.
A simpler solution using HSV like RogueBaneling suggested:
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
necessary. Move 0.8f
to an argument if needed.
If you want more simple and not accurately, below might 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;
}
Convert the color to a HSV array, then reduce the brightness by 20%, then convert HSV array back to RGB with HSVToColor
. Note: The value you are looking to change in the array will be the V
-value. (i.e., hsv[2]
)
This way you can select percentage of color and thus fetch a shade darker or a shade lighter
` int color = ((ColorDrawable)c2.getBackground()).getColor();
int colorLighter=-color*40/100+color;
int colorDarker=+color*40/100+color; `
colorlighter gives us a lighter shade of color from button's background
colordarker gives us a darker shade of color from button's background