RobotKarel314 - 1 year ago 80

Java Question

I know Color has a

`darker()`

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) ,
components[3]);
}
```

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)`

).