Java Color Blend alphaBlend(final Color src, final Color dst)

Here you can find the source of alphaBlend(final Color src, final Color dst)

Description

Blends the two colors taking into account their alpha.
If one of the two input colors implements the UIResource interface, the result color will also implement this interface.

License

Open Source License

Parameter

Parameter Description
src Source color to be blended into the destination color.
dst Destination color on which the source color is to be blended.

Return

Color resulting from the color blending.

Declaration

public static Color alphaBlend(final Color src, final Color dst) 

Method Source Code


//package com.java2s;
import javax.swing.plaf.ColorUIResource;
import javax.swing.plaf.UIResource;
import java.awt.Color;

public class Main {
    /**/*  www  . j  a v a2 s . co  m*/
     * Blends the two colors taking into account their alpha.<br>If one of the two input colors implements the {@link
     * UIResource} interface, the result color will also implement this interface.
     *
     * @param src Source color to be blended into the destination color.
     * @param dst Destination color on which the source color is to be blended.
     *
     * @return Color resulting from the color blending.
     */
    public static Color alphaBlend(final Color src, final Color dst) {
        Color blend;

        final float srcA = (float) src.getAlpha() / 255.0f;
        final float dstA = (float) dst.getAlpha() / 255.0f;
        final float outA = srcA + dstA * (1 - srcA);

        if (outA > 0) {
            final float outR = ((float) src.getRed() * srcA + (float) dst.getRed() * dstA * (1.0f - srcA)) / outA;
            final float outG = ((float) src.getGreen() * srcA + (float) dst.getGreen() * dstA * (1.0f - srcA))
                    / outA;
            final float outB = ((float) src.getBlue() * srcA + (float) dst.getBlue() * dstA * (1.0f - srcA)) / outA;
            blend = new Color((int) outR, (int) outG, (int) outB, (int) (outA * 255.0f));
        } else {
            blend = new Color(0, 0, 0, 0);
        }

        if ((src instanceof UIResource) || (dst instanceof UIResource)) {
            blend = new ColorUIResource(blend);
        }

        return blend;
    }
}

Related

  1. alphaBlend(Color o, int a)
  2. blend(Color a, Color b)
  3. blend(Color a, Color b, double val)
  4. blend(Color c0, Color c1)
  5. blend(Color c1, Color c2)