5

假设我有两种颜色。

public final static Color FAR = new Color(237, 237, 30);
public final static Color CLOSE = new Color(58, 237, 221);

如何在不浸入深色的情况下从一种颜色过渡到另一种颜色?

我想出了诸如

    double ratio = diff / range; // goes from 1 to 0
    int red = (int)Math.abs((ratio * FAR.getRed()) - ((1 - ratio) * CLOSE.getRed()));
    int green = (int)Math.abs((ratio * FAR.getGreen()) - ((1 - ratio) * CLOSE.getGreen()));
    int blue = (int)Math.abs((ratio * FAR.getBlue()) - ((1 - ratio) * CLOSE.getBlue()));

或者

    double ratio = diff / range; // goes from 1 to 0
    int red = (int) ((1 - (diff / range)) * FAR.getRed() + CLOSE.getRed() - FAR.getRed());
    int green = (int) ((1 - (diff / range)) * FAR.getGreen() + CLOSE.getGreen() - FAR.getGreen());
    int blue = (int) ((1 - (diff / range)) * FAR.getBlue() + CLOSE.getBlue() - FAR.getBlue());

但不幸的是,它们都没有从一种颜色平滑过渡到另一种颜色。有谁知道如何在保持颜色明亮而不陷入较暗颜色的同时做到这一点,或者如何确保渐变过渡是平滑的,而不是一开始就变慢,然后变快,然后又变慢?

我真的想不出任何公式。

4

3 回答 3

7

您在计算中使用了错误的符号。应该是正数,而不是负数,才能正确应用该比率。

int red = (int)Math.abs((ratio * FAR.getRed()) + ((1 - ratio) * CLOSE.getRed()));
int green = (int)Math.abs((ratio * FAR.getGreen()) + ((1 - ratio) * CLOSE.getGreen()));
int blue = (int)Math.abs((ratio * FAR.getBlue()) + ((1 - ratio) * CLOSE.getBlue()));

您使用现有实现获得深色的原因是,使用 (-),它们通常会接近于零(小于 50?或负但大于 -50?),并且在负面情况下,您正在接受绝对值,所以它变成一个小的正数,即深色。

于 2013-11-07T16:41:28.670 回答
1
(ratio * FAR.getGreen()) + ((1 - ratio) * CLOSE.getGreen())

如果比率从 0 变为 1,那么这是加权平均,假设比率 = 1/2,那么它将是算术平均,如果比率 = 1/3,那么它是加权平均,其中 FAR 的权重为 1,CLOSE 的权重2

于 2013-11-07T16:41:28.167 回答
1

这对我很有效:

// Steps between fading from one colour to another.
private static final int FadeSteps = 25;

private void fade(Label panel, Color colour) throws InterruptedException {
  final Color oldColour = panel.getBackground();
  final int dRed = colour.getRed() - oldColour.getRed();
  final int dGreen = colour.getGreen() - oldColour.getGreen();
  final int dBlue = colour.getBlue() - oldColour.getBlue();
  // No point if no difference.
  if (dRed != 0 || dGreen != 0 || dBlue != 0) {
    // Do it in n steps.
    for (int i = 0; i <= FadeSteps; i++) {
      final Color c = new Color(
              oldColour.getRed() + ((dRed * i) / FadeSteps),
              oldColour.getGreen() + ((dGreen * i) / FadeSteps),
              oldColour.getBlue() + ((dBlue * i) / FadeSteps));
      panel.setBackground(c);
      Thread.sleep(10);
    }
  }
}

不是最整洁的代码,但它可以工作。

于 2013-11-07T16:49:29.237 回答