ColorInterpolator.java

  1. package org.opentrafficsim.draw;

  2. import java.awt.Color;

  3. /**
  4.  * Interpolate between two color values.
  5.  * <p>
  6.  * Copyright (c) 2013-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
  7.  * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
  8.  * </p>
  9.  * @author <a href="https://tudelft.nl/staff/p.knoppers-1">Peter Knoppers</a>
  10.  */
  11. public final class ColorInterpolator
  12. {
  13.     /** Static use only; this class cannot be instantiated. */
  14.     private ColorInterpolator()
  15.     {
  16.         // Cannot be instantiated
  17.     }

  18.     /**
  19.      * Generate a Color that is interpolated between two given Color values. Interpolation is simply done per channel (R, G, B).
  20.      * @param zero Color; the color that corresponds to ratio == 0
  21.      * @param one Color; the color that corresponds to ratio == 1
  22.      * @param ratio double; the ratio (should be between 0 and 1)
  23.      * @return Color; the interpolated color
  24.      */
  25.     public static Color interpolateColor(final Color zero, final Color one, final double ratio)
  26.     {
  27.         if (ratio < 0 || ratio > 1)
  28.         {
  29.             throw new RuntimeException("Bad ratio (should be between 0 and 1; got " + ratio + ")");
  30.         }
  31.         double complement = 1 - ratio;
  32.         return new Color((int) (zero.getRed() * complement + one.getRed() * ratio),
  33.                 (int) (zero.getGreen() * complement + one.getGreen() * ratio),
  34.                 (int) (zero.getBlue() * complement + one.getBlue() * ratio));
  35.     }
  36. }