Blend two colors. - Java 2D Graphics

Java examples for 2D Graphics:Color Blend

Description

Blend two colors.

Demo Code

/*/*from   www. ja v  a2  s  .c  om*/
Storybook: Scene-based software for novelists and authors.
Copyright (C) 2008 - 2011 Martin Mustun

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
import java.awt.Color;

public class Main{
    /**
     * Blend two colors.
     *
     * @param color1
     *            First color to blend.
     * @param color2
     *            Second color to blend.
     * @param ratio
     *            Blend ratio. 0.5 will give even blend, 1.0 will return color1,
     *            0.0 will return color2 and so on.
     * @return Blended color.
     */
    public static Color blend(Color color1, Color color2, double ratio) {
        float r = (float) ratio;
        float ir = (float) 1.0 - r;

        float rgb1[] = new float[3];
        float rgb2[] = new float[3];

        color1.getColorComponents(rgb1);
        color2.getColorComponents(rgb2);

        Color color = new Color(rgb1[0] * r + rgb2[0] * ir, rgb1[1] * r
                + rgb2[1] * ir, rgb1[2] * r + rgb2[2] * ir);

        return color;
    }
    /**
     * Make an even blend between two colors.
     *
     * @param c1
     *            First color to blend.
     * @param c2
     *            Second color to blend.
     * @return Blended color.
     */
    public static Color blend(Color color1, Color color2) {
        return ColorUtil.blend(color1, color2, 0.5);
    }
}

Related Tutorials