RobotKarel314 RobotKarel314 - 2 years ago 93
Java Question

Make a java color less dark?

I know Color has a

method that returns a darker version of a color. Is there a way to change the factor (I believe it is 0.7) in which Color does so, thereby making a Color less/more dark (or conversely, less/more bright)?

From the Java API:

This method applies an arbitrary scale factor to each of the three RGB components of this Color to create a darker version of this Color.

In other words, can I change this arbitrary scale factor?

Answer Source

The javaAPI doesn't provide any utility for this. Anyways, it's pretty trivial, so why not code it yourself?

Color overrideBrightness(Color c , float factor){
    if(factor < 0)
        throw new IllegalArgumentException("Factor must be positive");

    float[] components = c.getComponents();

    return new Color(Math.min(components[0] * factor , 1.0) , 
                     Math.min(components[1] * factor , 1.0) ,
                     Math.min(components[2] * factor , 1.0) , 

For factor > 1, the color becomes brighter, for factor < 1, the color becomes darker. This method should be reversible, except for some rounding-errors.

Note this method doesn't handle extreme cases, like overflow for factor close to Float.MAX_VALUE and won't work for perfect black (new Color(0.0, 0.0, 0.0)).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download