Compute a darker color - Java 2D Graphics

Java examples for 2D Graphics:Color Dark

Description

Compute a darker color

Demo Code


import java.awt.Color;

public class Main{
    /**//from  w  w  w .  j a  va2 s.c  o m
     * Compute a darker color
     * 
     * @param color
     *           Base color
     * @return Darker color
     */
    public static Color moreDark(final Color color) {
        return ColorsUtil.changeBright(color, 0.5f);
    }
    /**
     * Change color bright
     * 
     * @param color
     *           Base color
     * @param factor
     *           Bright factor (factor>1 => more bright | 0<factor<1 => more dark)
     * @return Computed color
     */
    public static Color changeBright(final Color color, final float factor) {
        // Get color parts
        int red = color.getRed();
        int green = color.getGreen();
        int blue = color.getBlue();

        // Convert in YUV
        double y = (red * 0.299) + (green * 0.587) + (blue * 0.114);
        final double u = ((-0.169 * red) - (0.331 * green))
                + (0.500 * blue) + 128.0;
        final double v = ((0.500 * red) - (0.419 * green) - (0.081 * blue)) + 128.0;

        // Apply the factor
        y *= factor;

        // Convert to RGB
        red = ColorsUtil.limite0_255((y - (0.0009267 * (u - 128)))
                + (1.4016868 * (v - 128)));
        green = ColorsUtil.limite0_255(y - (0.3436954 * (u - 128))
                - (0.7141690 * (v - 128)));
        blue = ColorsUtil.limite0_255(y + (1.7721604 * (u - 128))
                + (0.0009902 * (v - 128)));

        // Return the new color
        return new Color(red, green, blue);
    }
    /**
     * Take the integer part of a number and put it in [0, 255]<br>
     * That is to say if integer<0, return 0. If integer>255, return 2555. Return the integer on other case
     * 
     * @param number
     *           Number to limit
     * @return Limited value
     */
    public static int limite0_255(final double number) {
        final int integer = (int) number;
        if (integer < 0) {
            return 0;
        }
        if (integer > 255) {
            return 255;
        }
        return integer;
    }
}

Related Tutorials