Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import android.graphics.Color;

public class Main {
    /**
     *  Convert RGB Color to a HSL values.
     *  
     *  <li>H (Hue) is specified as degrees in the range 0 - 360.</li>
     *  <li>S (Saturation) is specified as a percentage in the range 1 - 100.</li>
     *  <li>L (Lumanance) is specified as a percentage in the range 1 - 100.</li>
     *
     *  @param color the RGB color
     *  @return the HSL values
     */
    public static int[] colorToHSL(int color) {
        int[] hsl = new int[3];
        float[] hsl_float = hslFromRGB(color);

        hsl[0] = (int) Math.round(hsl_float[0]);
        hsl[1] = (int) Math.round(hsl_float[1]);
        hsl[2] = (int) Math.round(hsl_float[2]);

        return hsl;
    }

    /**
     *  Convert a RGB Color to it corresponding HSL values.
     *
     *  @return an array containing the 3 HSL values.
     */
    public static float[] hslFromRGB(int color) {
        //  Get RGB values in the range 0 - 1
        float r = (float) Color.red(color) / 255.0f;
        float g = (float) Color.green(color) / 255.0f;
        float b = (float) Color.blue(color) / 255.0f;

        //  Minimum and Maximum RGB values are used in the HSL calculations
        float min = Math.min(r, Math.min(g, b));
        float max = Math.max(r, Math.max(g, b));

        //  Calculate the Hue
        float h = 0;

        if (max == min)
            h = 0;
        else if (max == r)
            h = ((60 * (g - b) / (max - min)) + 360) % 360;
        else if (max == g)
            h = (60 * (b - r) / (max - min)) + 120;
        else if (max == b)
            h = (60 * (r - g) / (max - min)) + 240;

        //  Calculate the Luminance
        float l = (max + min) / 2;

        //  Calculate the Saturation
        float s = 0;

        if (max == min)
            s = 0;
        else if (l <= .5f)
            s = (max - min) / (max + min);
        else
            s = (max - min) / (2 - max - min);

        return new float[] { h, s * 100, l * 100 };
    }
}