Mixes two colors. - Java 2D Graphics

Java examples for 2D Graphics:Color Blend

Description

Mixes two colors.

Demo Code

/*//from   w  w  w  .  ja  v  a 2 s  .  co  m
 * Copyright (c) 2008 Pierre Dragicevic <dragice@lri.fr>
 *
 *  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/>.
 */
//package com.java2s;

import java.awt.Color;

public class Main {
    /**
     * Mixes two colors.
     */
    public static Color mix(Color c0, Color c1, float amount) {
        if (c0.equals(c1))
            return c0;
        if (amount == 0)
            return c0;
        if (amount == 1)
            return c1;
        float r0 = c0.getRed() / 255f;
        float g0 = c0.getGreen() / 255f;
        float b0 = c0.getBlue() / 255f;
        float a0 = c0.getAlpha() / 255f;
        float r1 = c1.getRed() / 255f;
        float g1 = c1.getGreen() / 255f;
        float b1 = c1.getBlue() / 255f;
        float a1 = c1.getAlpha() / 255f;
        return new Color(bound01(r0 + (r1 - r0) * amount), bound01(g0
                + (g1 - g0) * amount), bound01(b0 + (b1 - b0) * amount),
                bound01(a0 + (a1 - a0) * amount));
    }

    private static float bound01(float x) {
        if (x < 0)
            x = 0;
        if (x > 1)
            x = 1;
        return x;
    }
}

Related Tutorials