Here you can find the source of contrastColorByShift(Color color, int shift)
Parameter | Description |
---|---|
color | the color we want to create a contrast for |
shift | the shift value |
public static Color contrastColorByShift(Color color, int shift)
//package com.java2s; /*// ww w .j a va 2 s . c o m * Copyright (C) 2015 Dieter J Kybelksties * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * @date: 2015-12-16 * @author: Dieter J Kybelksties */ import java.awt.Color; public class Main { /** * Create a contrasting RGB color to a color by shifting the color (making * it brighter or darker) so that if used as foreground/background they are * different enough to be readable. * * @param color the color we want to create a contrast for * @param shift the shift value * @return the contrast color */ public static Color contrastColorByShift(Color color, int shift) { float alpha = (color == null) ? 1.0F : color.getAlpha() / 256.0F; if (color == null) { color = Color.BLACK; } if (shift < 1) { shift = 128; } int r1 = color.getRed(); int g1 = color.getGreen(); int b1 = color.getBlue(); float r2 = (float) ((r1 + shift) % 256) / 256.0F; float g2 = (float) ((g1 + shift) % 256) / 256.0F; float b2 = (float) ((b1 + shift) % 256) / 256.0F; Color reval = makeColor(r2, g2, b2, alpha); return reval; } /** * Create a color with RGB values and by ensuring they are in legal range * [0..255]. * * @param r red * @param g green * @param b blue * @return the color object */ public static Color makeColor(int r, int g, int b) { r = (r < 0) ? 0 : r; r = (r > 255) ? 255 : r; g = (g < 0) ? 0 : g; g = (g > 255) ? 255 : g; b = (b < 0) ? 0 : b; b = (b > 255) ? 255 : b; return new Color(r, g, b); } /** * Create a color with RGB values and by ensuring they are in legal range * [0..255]. * * @param r red * @param g green * @param b blue * @param a transparency * @return the color object */ public static Color makeColor(float r, float g, float b, float a) { r = (r < 0.0F) ? 0.0F : r; r = (r > 1.0F) ? 1.0F : r; g = (g < 0.0F) ? 0.0F : g; g = (g > 1.0F) ? 1.0F : g; b = (b < 0.0F) ? 0.0F : b; b = (b > 1.0F) ? 1.0F : b; a = (a < 0.0F) ? 0.0F : a; a = (a > 1.0F) ? 1.0F : a; return new Color(r, g, b, a); } }