blend Between Colors - Java 2D Graphics

Java examples for 2D Graphics:Color Blend

Description

blend Between Colors

Demo Code


//package com.java2s;

public class Main {
    public static int blendBetweenColors(double val, int minColor,
            int maxColor) {
        return blendBetweenColors(val, minColor, maxColor, 0d, 1d);
    }//from w w w .j av a2s .c om

    public static int blendBetweenColors(double val, int minColor,
            int maxColor, double min, double max) {
        if (min == max)
            return maxColor;

        double range = max - min;
        double ratioOfMax = (max - val) / range;
        double ratioOfMin = (val - min) / range;

        int[] minColorRGBA = toRGBA(minColor);
        int[] maxColorRGBA = toRGBA(maxColor);
        int[] color = new int[] {
                (int) (maxColorRGBA[0] * ratioOfMin + minColorRGBA[0]
                        * ratioOfMax),
                (int) (maxColorRGBA[1] * ratioOfMin + minColorRGBA[1]
                        * ratioOfMax),
                (int) (maxColorRGBA[2] * ratioOfMin + minColorRGBA[2]
                        * ratioOfMax),
                (int) (maxColorRGBA[3] * ratioOfMin + minColorRGBA[3]
                        * ratioOfMax) };

        return fromRGBA(color[0], color[1], color[2], color[3]);
    }

    public static int[] toRGBA(int color) {
        int alpha = color >> 24 & 255;
        int red = color >> 16 & 255;
        int green = color >> 8 & 255;
        int blue = color & 255;

        return new int[] { red, green, blue, alpha };
    }

    public static int fromRGBA(int r, int g, int b, int a) {
        return (a & 255) << 24 | (r & 255) << 16 | (g & 255) << 8 | b & 255;
    }
}

Related Tutorials