Java Color Blend blend(Color pColor, Color pOther)

Here you can find the source of blend(Color pColor, Color pOther)

Description

Blends two colors half and half, to create a tone in between.

License

Open Source License

Parameter

Parameter Description
pColor color 1
pOther color 2

Return

a new Color

Declaration

public static Color blend(Color pColor, Color pOther) 

Method Source Code


//package com.java2s;
import java.awt.*;

public class Main {
    /**/*from  w w  w .ja  va2s  . c o  m*/
     * Blends two ARGB values half and half, to create a tone in between.
     *
     * @param pRGB1 color 1
     * @param pRGB2 color 2
     * @return the new rgb value
     */
    static int blend(int pRGB1, int pRGB2) {
        // Slightly modified from http://www.compuphase.com/graphic/scale3.htm
        // to support alpha values
        return (((pRGB1 ^ pRGB2) & 0xfefefefe) >> 1) + (pRGB1 & pRGB2);
    }

    /**
     * Blends two colors half and half, to create a tone in between.
     *
     * @param pColor color 1
     * @param pOther color 2
     * @return a new {@code Color}
     */
    public static Color blend(Color pColor, Color pOther) {
        return new Color(blend(pColor.getRGB(), pOther.getRGB()), true);

        /*
        return new Color((pColor.getRed() + pOther.getRed()) / 2,
        (pColor.getGreen() + pOther.getGreen()) / 2,
        (pColor.getBlue() + pOther.getBlue()) / 2,
        (pColor.getAlpha() + pOther.getAlpha()) / 2);
        */
    }

    /**
     * Blends two colors, controlled by the blending factor.
     * A factor of {@code 0.0} will return the first color,
     * a factor of {@code 1.0} will return the second.
     *
     * @param pColor color 1
     * @param pOther color 2
     * @param pBlendFactor {@code [0...1]}
     * @return a new {@code Color}
     */
    public static Color blend(Color pColor, Color pOther, float pBlendFactor) {
        float inverseBlend = (1f - pBlendFactor);
        return new Color(clamp((pColor.getRed() * inverseBlend) + (pOther.getRed() * pBlendFactor)),
                clamp((pColor.getGreen() * inverseBlend) + (pOther.getGreen() * pBlendFactor)),
                clamp((pColor.getBlue() * inverseBlend) + (pOther.getBlue() * pBlendFactor)),
                clamp((pColor.getAlpha() * inverseBlend) + (pOther.getAlpha() * pBlendFactor)));
    }

    private static int clamp(float f) {
        return (int) f;
    }
}

Related

  1. blend(Color cFrom, Color cTo, float factor)
  2. blend(Color col1, Color col2, float weight1)
  3. blend(Color color1, Color color2, float ratio)
  4. blend(Color color1, Color color2, int factor)
  5. blend(Color origin, Color over)
  6. blend(double factor, Color color1, Color color2)
  7. blend(final Color color1, final Color color2, final double ratio)
  8. blend(final Color first, final Color second, final float alpha)
  9. blendAlpha(Color under, Color over)