Java平滑颜色过渡

时间:2013-11-07 16:36:28

标签: java algorithm colors

假设我有两种颜色。

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

OR

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

但不幸的是,它们都没有顺利地从一种颜色过渡到另一种颜色。 有人知道怎么做,同时保持颜色明亮而不是深入颜色,或者如何确保渐变过渡是平滑的而不是先减速然后快速然后再慢化?

我真的没有提出任何公式。

3 个答案:

答案 0 :(得分:6)

你在计算中使用了错误的符号。应该是加号而不是减号来正确应用这个比例。

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?)而在负面情况下,嗯,你正在取绝对值,所以它变成一个小的正数,即暗色。

答案 1 :(得分:2)

这对我很有用:

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

不是最新的代码,但它有效。

答案 2 :(得分:1)

(ratio * FAR.getGreen()) + ((1 - ratio) * CLOSE.getGreen())

如果比率从0到1,那么这是加权平均值,比如说= 1/2,那么它将是aritmetical average,如果ratio = 1/3,那么它是加权平均值,其中FAR具有权重1和CLOSE的重量为2