Using color and color.darker in Android? Using color and color.darker in Android? java java

Using color and color.darker in Android?


The easiest, I think, would be to convert to HSV, do the darkening there, and convert back:

float[] hsv = new float[3];int color = getColor();Color.colorToHSV(color, hsv);hsv[2] *= 0.8f; // value componentcolor = Color.HSVToColor(hsv);

To lighten, a simple approach may be to multiply the value component by something > 1.0. However, you'll have to clamp the result to the range [0.0, 1.0]. Also, simply multiplying isn't going to lighten black.

Therefore a better solution is: Reduce the difference from 1.0 of the value component to lighten:

hsv[2] = 1.0f - 0.8f * (1.0f - hsv[2]);

This is entirely parallel to the approach for darkening, just using 1 as the origin instead of 0. It works to lighten any color (even black) and doesn't need any clamping. It could be simplified to:

hsv[2] = 0.2f + 0.8f * hsv[2];

However, because of possible rounding effects of floating point arithmetic, I'd be concerned that the result might exceed 1.0f (by perhaps one bit). Better to stick to the slightly more complicated formula.


Here is what I created:

/** * Returns darker version of specified <code>color</code>. */public static int darker (int color, float factor) {    int a = Color.alpha( color );    int r = Color.red( color );    int g = Color.green( color );    int b = Color.blue( color );    return Color.argb( a,            Math.max( (int)(r * factor), 0 ),            Math.max( (int)(g * factor), 0 ),            Math.max( (int)(b * factor), 0 ) );}


Ted's answer to lighten a color wasn't working for me so here is a solution that might help someone else:

/** * Lightens a color by a given factor. *  * @param color *            The color to lighten * @param factor *            The factor to lighten the color. 0 will make the color unchanged. 1 will make the *            color white. * @return lighter version of the specified color. */public static int lighter(int color, float factor) {    int red = (int) ((Color.red(color) * (1 - factor) / 255 + factor) * 255);    int green = (int) ((Color.green(color) * (1 - factor) / 255 + factor) * 255);    int blue = (int) ((Color.blue(color) * (1 - factor) / 255 + factor) * 255);    return Color.argb(Color.alpha(color), red, green, blue);}