【问题标题】:Java: Operations with Colors (add, subtract)? - Colors in a constant classJava:颜色运算(加、减)? - 常量类中的颜色
【发布时间】:2010-12-09 17:51:10
【问题描述】:

我正在使用java.awt.Color 实例。有没有办法对颜色进行算术运算? rgb(20, 20, 20) + rgb(10, 200, 170) = rgb(30, 220, 190) 之类的东西?

我正在尝试做的事情:我有一个带有表格的 gui,如果用户单击一个单元格,其他单元格会根据它们与所选单元格的关系改变颜色。我正在寻找一种方法来避免硬编码基本颜色是什么,以及它们改变的颜色值。

因此选定的单元格可能是rgb(255, 0, 0),其他所有单元格都可能介于rgb(0, 0, 0)rgb(0, 255, 0) 之间,具体取决于它们的值。我在想...枚举?

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;

}

【问题讨论】:

    标签: java colors operators enums rgb


    【解决方案1】:

    HSLColor 可能是您正在寻找的。它使您可以轻松调整颜色的色调/阴影。

    【讨论】:

    • new HslColor(new HslColor(48.0,100.0, 50.0).adjustHue(60.0)).getSaturation() 返回100.0000002 在此之后任何调整都会引发错误非法参数饱和超出范围。你能帮我吗?? new HslColor(new HslColor(48.0,100.0, 50.0).adjustHue(180.0)).getSaturation() 返回 100.0000002
    • new HslColor(48.0, 100.0, 50.0).adjustHue(60.0) 正在返回一个 java.awt.Color,其红色分量为 1.00001 > 1 :(
    【解决方案2】:

    有 Color.brighter 和 Color.darker 方法。

    除此之外,我通常会为此编写一些实用的小方法,例如:

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

    【讨论】:

    • 老兄!从来没有想过使用 Math.min,但它确实是有道理的! D:
    猜你喜欢
    • 2013-07-06
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 2014-03-27
    • 2012-07-07
    • 2013-07-03
    • 2011-11-26
    • 1970-01-01
    相关资源
    最近更新 更多