Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using color and color.darker in Android?

Okay, so I have an integer variable in my application. It's the value of a color, being set by a color picker in my preferences. Now, I need to use both that color and a darker version of any color it might be.

Now I know in standard Java there is a Color.darker() method, but there doesn't seem to be an equivalent in Android. Does anyone know of an equivalent or any workarounds?

like image 498
Nick Avatar asked Feb 08 '11 01:02

Nick


People also ask

How do I manage Dark mode on Android?

Use the system setting (Settings -> Display -> Theme) to enable Dark theme. Use the Quick Settings tile to switch themes from the notification tray (once enabled).

How do you turn on invert colors on Android?

Turn on color inversionOpen your device's Settings app . Select Accessibility. Under "Display," select Color inversion. Turn on Use color inversion.

How do you make a color darker and lighter?

Tints are lighter versions of the color that are made by mixing a color with white, whereas shades are darker versions of the color that are made by mixing a color with black.


1 Answers

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 component color = 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.

like image 94
Ted Hopp Avatar answered Oct 01 '22 23:10

Ted Hopp