Java Color Mix mix(Color c1, Color c2, boolean useAlpha)

Here you can find the source of mix(Color c1, Color c2, boolean useAlpha)

Description

Mix 2 colors without "priority" color

License

Open Source License

Declaration

public static Color mix(Color c1, Color c2, boolean useAlpha) 

Method Source Code


//package com.java2s;
/*//from   w w  w.  j a v  a 2s.  c o  m
 * Copyright 2010, 2011 Institut Pasteur.
 * 
 * This file is part of ICY.
 * 
 * ICY 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.
 * 
 * ICY 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 ICY. If not, see <http://www.gnu.org/licenses/>.
 */

import java.awt.Color;

public class Main {
    /**
     * Mix 2 colors without "priority" color
     */
    public static Color mix(Color c1, Color c2, boolean useAlpha) {
        final int r, g, b, a;

        if (useAlpha) {
            final float a1 = c1.getAlpha() / 255f;
            final float a2 = c2.getAlpha() / 255f;
            final float af = a1 + a2;

            r = (int) (((c1.getRed() * a1) + (c2.getRed() * a2)) / af);
            g = (int) (((c1.getGreen() * a1) + (c2.getGreen() * a2)) / af);
            b = (int) (((c1.getBlue() * a1) + (c2.getBlue() * a2)) / af);
            a = Math.max(c1.getAlpha(), c2.getAlpha());
        } else {
            r = (c1.getRed() + c2.getRed()) / 2;
            g = (c1.getGreen() + c2.getGreen()) / 2;
            b = (c1.getBlue() + c2.getBlue()) / 2;
            a = 255;
        }

        return new Color(r, g, b, a);
    }

    /**
     * Mix 2 colors (no alpha)
     */
    public static Color mix(Color c1, Color c2) {
        return mix(c1, c2, false);
    }
}

Related

  1. mix(Color a, Color b, double percent)
  2. mix(Color c0, Color c1, float amount)
  3. mix(Color c1, Color c2)
  4. mix(Color c1, Color c2)
  5. mix(Color c1, Color c2, double f)
  6. mix(Color c1, Color c2, float bias)
  7. mix(Color src, Color dst, double factor)
  8. mix(double x, double y, double a)