Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Operations with Colors (add, subtract)? - Colors in a constant class

I'm working with java.awt.Color instances. Is there any way to do arithmetic operations on colors? Something like rgb(20, 20, 20) + rgb(10, 200, 170) = rgb(30, 220, 190)?

What I'm trying to do: I have a gui that features a table, where if the user clicks on a cell, the other cells change color based on their relationship to the selected one. I'm looking for a way to avoid hard coding what the base colors are, and on which color values they change.

So the selected cell might be rgb(255, 0, 0), and everything else might be between rgb(0, 0, 0) and rgb(0, 255, 0) based on their values. I'm thinking... enums?

import java.awt.Color;

public enum ColorConstant {
    SELECTED (new rgb(255, 0, 0), "Red"),
    MAX_DISTANCE (new rgb(0, 255, 0), "Green")

    private Color shade;
    private ??? whichColorToModify;

}
like image 664
Nick Heiner Avatar asked Jan 23 '23 02:01

Nick Heiner


2 Answers

There are the methods Color.brighter and Color.darker.

Other than that, I usually write a small utility methods for such purposes, like:

private static Color brightness(Color c, double scale) {
    int r = Math.min(255, (int) (c.getRed() * scale));
    int g = Math.min(255, (int) (c.getGreen() * scale));
    int b = Math.min(255, (int) (c.getBlue() * scale));
    return new Color(r,g,b);
}
like image 177
meriton Avatar answered Jan 31 '23 23:01

meriton


HSLColor might be what you are looking for. It allow you to adjust the tone/shade of a color easily.

like image 34
camickr Avatar answered Jan 31 '23 23:01

camickr