Java tutorial
//package com.java2s; /* * Copyright 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.graphics.Color; public class Main { /** * Convert the ARGB color to its HSL (hue-saturation-lightness) components. * <ul> * <li>outHsl[0] is Hue [0 .. 360)</li> * <li>outHsl[1] is Saturation [0...1]</li> * <li>outHsl[2] is Lightness [0...1]</li> * </ul> * * @param color the ARGB color to convert. The alpha component is ignored * @param outHsl 3-element array which holds the resulting HSL components */ public static void colorToHSL(int color, float[] outHsl) { RGBToHSL(Color.red(color), Color.green(color), Color.blue(color), outHsl); } /** * Convert RGB components to HSL (hue-saturation-lightness). * <ul> * <li>outHsl[0] is Hue [0 .. 360)</li> * <li>outHsl[1] is Saturation [0...1]</li> * <li>outHsl[2] is Lightness [0...1]</li> * </ul> * * @param r red component value [0..255] * @param g green component value [0..255] * @param b blue component value [0..255] * @param outHsl 3-element array which holds the resulting HSL components */ public static void RGBToHSL(int r, int g, int b, float[] outHsl) { final float rf = r / 255f; final float gf = g / 255f; final float bf = b / 255f; final float max = Math.max(rf, Math.max(gf, bf)); final float min = Math.min(rf, Math.min(gf, bf)); final float deltaMaxMin = max - min; float h, s; float l = (max + min) / 2f; if (max == min) { // Monochromatic h = s = 0f; } else { if (max == rf) { h = ((gf - bf) / deltaMaxMin) % 6f; } else if (max == gf) { h = ((bf - rf) / deltaMaxMin) + 2f; } else { h = ((rf - gf) / deltaMaxMin) + 4f; } s = deltaMaxMin / (1f - Math.abs(2f * l - 1f)); } h = (h * 60f) % 360f; if (h < 0) { h += 360f; } outHsl[0] = constrain(h, 0f, 360f); outHsl[1] = constrain(s, 0f, 1f); outHsl[2] = constrain(l, 0f, 1f); } private static float constrain(float amount, float low, float high) { return amount < low ? low : (amount > high ? high : amount); } private static int constrain(int amount, int low, int high) { return amount < low ? low : (amount > high ? high : amount); } }