How to darken a given color (int)

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.


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.