Returns white or black text depending on the background. - Java 2D Graphics

Java examples for 2D Graphics:Color

Description

Returns white or black text depending on the background.

Demo Code

/*/*from  w  w w  . j  a v  a2  s .  c om*/
 * This file is part of Creative Application Framework (CAF).
 *
 * The Core Application Framework is free software: you can redistribute it
 * and/or modify it under the terms of the GNU Lesser General Public License
 * as published  by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * The Core Application Framework is distributed in the hope that it
 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Core Application Framework.  If not, 
 * see <http://www.gnu.org/licenses/>.
 * 
 */
import java.awt.Color;
import org.apache.log4j.Logger;

public class Main{
    /**
     * Returns white or black text depending on the background.
     * See here http://www.codeproject.com/KB/GDI-plus/IdealTextColor.aspx
     * @param background
     * @return
     */
    public static Color getTextColor(Color background) {
        int threshold = 105;
        int delta = (int) ((background.getRed() * 0.299)
                + (background.getGreen() * 0.587) + (background.getBlue() * 0.114));

        return (255 - delta < threshold) ? Color.BLACK : Color.WHITE;
    }
}

Related Tutorials