This method uses HSL to determine in a human eyesight terms if a color is light or not. - Android Graphics

Android examples for Graphics:Color

Description

This method uses HSL to determine in a human eyesight terms if a color is light or not.

Demo Code

/*/*from  w ww .ja  v  a 2  s .  c  om*/
 * Copyright (C) 2015 Twitter, Inc.
 *
 * 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.
 *
 */
//package com.java2s;
import android.graphics.Color;

public class Main {
    private static final int RGB_TOTAL_COLORS = 256;
    private static final float DEFAULT_LIGHTNESS_THRESHOLD = .6f;

    public static boolean isLightColor(final int color) {
        return isLightColor(color, DEFAULT_LIGHTNESS_THRESHOLD);
    }

    /**
     * This method uses HSL to determine in a human eyesight terms if a color is light or not.
     * See: http://en.wikipedia.org/wiki/HSL_and_HSV. The threshold values are from ITU Rec. 709
     * http://en.wikipedia.org/wiki/Rec._709#Luma_coefficients
     *
     *
     * @param  color A color value
     * @param  factor A factor of lightness measured between 0-1.0
     * @return Whether or not the color is considered light
     */
    public static boolean isLightColor(final int color, final float factor) {
        final int r = Color.red(color);
        final int g = Color.green(color);
        final int b = Color.blue(color);

        final double threshold = 0.21 * r + 0.72 * g + 0.07 * b;
        return threshold > (RGB_TOTAL_COLORS * factor);
    }
}

Related Tutorials