Java平滑颜色过渡

``````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 个答案:

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

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

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