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

泄露秘密 提交于 2019-12-06 10:34:13

问题


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;

}

回答1:


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);
}



回答2:


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



来源:https://stackoverflow.com/questions/1618169/java-operations-with-colors-add-subtract-colors-in-a-constant-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!