get Text Color from background color - Java 2D Graphics

Java examples for 2D Graphics:Text

Description

get Text Color from background color

Demo Code

/**//from ww w .  j a v  a  2  s . c o  m
 * Copyright 1998-2008, CHISEL Group, University of Victoria, Victoria, BC, Canada.
 * All rights reserved.
 */
//package com.java2s;
import java.awt.Color;

public class Main {
    /**
     * @param bgColor
     * @return Black or white, depeding on the "darkness" of bgColor.
     */
    public static Color getTextColor(Color bgColor) {
        Color textColor = Color.black;
        //      float[] hsbVals = null;
        //      hsbVals = Color.RGBtoHSB(bgColor.getRed(), bgColor.getGreen(), bgColor.getBlue(), hsbVals);
        //      if (hsbVals[2] <= 0.8f) {
        //         textColor = Color.white; // if the background is dark then make the text color white
        //      }

        // use white if the sum of red (0-255), green and blue is small
        if (bgColor != null) {
            int rgb = bgColor.getRed() + bgColor.getGreen()
                    + bgColor.getBlue();
            if (rgb < 400) {
                textColor = Color.white;
            }
        }
        return textColor;
    }
}

Related Tutorials