Blends two colors to create a new color. - Java 2D Graphics

Java examples for 2D Graphics:Color Blend

Description

Blends two colors to create a new color.

Demo Code

/*/* ww w . j  ava  2s . c o  m*/
 * $Id: ColorUtil.java 3742 2010-08-05 03:25:09Z kschaefe $
 *
 * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle,
 * Santa Clara, California 95054, U.S.A. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library 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
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
//package com.java2s;
import java.awt.Color;

public class Main {
    /**
     * Blends two colors to create a new color. The {@code origin} color is the
     * base for the new color and regardless of its alpha component, it is
     * treated as fully opaque (alpha 255).
     * 
     * @param origin
     *            the base of the new color
     * @param over
     *            the alpha-enabled color to add to the {@code origin} color
     * @return a new color comprised of the {@code origin} and {@code over}
     *         colors
     */
    public static Color blend(Color origin, Color over) {
        if (over == null) {
            return origin;
        }

        if (origin == null) {
            return over;
        }

        int a = over.getAlpha();

        int rb = (((over.getRGB() & 0x00ff00ff) * (a + 1)) + ((origin
                .getRGB() & 0x00ff00ff) * (0xff - a))) & 0xff00ff00;
        int g = (((over.getRGB() & 0x0000ff00) * (a + 1)) + ((origin
                .getRGB() & 0x0000ff00) * (0xff - a))) & 0x00ff0000;

        return new Color((over.getRGB() & 0xff000000) | ((rb | g) >> 8));
    }
}

Related Tutorials