Linearly blends two colors with a defined weight. - Java 2D Graphics

Java examples for 2D Graphics:Line

Description

Linearly blends two colors with a defined weight.

Demo Code


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.font.FontRenderContext;
import java.awt.font.LineBreakMeasurer;
import java.awt.font.TextAttribute;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Rectangle2D;
import java.text.AttributedCharacterIterator;
import java.text.AttributedString;
import java.util.LinkedList;
import java.util.List;

public class Main{
    /**//from w  w w. j  a v a  2  s  .  c o m
     * Linearly blends two colors with a defined weight.
     *
     * @param color1 First color.
     * @param color2 Second color.
     * @param weight Weighting factor in the range 0 to 1 (0 means color1, 1
     *               means second color)
     * @return New blended color
     */
    public static Color blend(Color color1, Color color2, double weight) {
        double w2 = MathUtils.limit(weight, 0.0, 1.0);
        double w1 = 1.0 - w2;
        int r = (int) Math.round(w1 * color1.getRed() + w2
                * color2.getRed());
        int g = (int) Math.round(w1 * color1.getGreen() + w2
                * color2.getGreen());
        int b = (int) Math.round(w1 * color1.getBlue() + w2
                * color2.getBlue());
        int a = (int) Math.round(w1 * color1.getAlpha() + w2
                * color2.getAlpha());
        return new Color(r, g, b, a);
    }
}

Related Tutorials