用HSV模型来实现颜色的随机,然后转为RGB模型
- 色相(H)是色彩的基本属性,就是平常所说的颜色名称,如红色、黄色等。
- 饱和度(S)是指色彩的纯度,越高色彩越纯,低则逐渐变灰,取0-100%的数值。
- 明度(V),亮度(L),取0-100%。
后两项如果写成固定值的话,那么色调会比较统一,以下为代码
import java.util.Random; public class RandomColorUtil{ private static Random random = new Random(); private float k = random.nextFloat() * 360; public static void main(String[] args) { RandomColorUtild = new RandomColorUtil(); for (int i = 0; i < 10; i++) { Color c = d.randomColor(); System.out.println(((int) c.r) + " " + ((int) c.g) + " " + ((int) c.b)); } } public Color randomColor() { return HSVtoRGB(randomH(), 0.8F, 0.8F); } private float randomH() { k += (1 - 0.618f) * 360; if (k > 360) k -= 360; return k; } private Color HSVtoRGB(float h, float s, float v) { float f, p, q, t; if (s == 0) { return makeColor(v, v, v); } h /= 60; int i = (int) Math.floor(h); f = h - i; p = v * (1 - s); q = v * (1 - s * f); t = v * (1 - s * (1 - f)); switch (i) { case 0: return makeColor(v, t, p); case 1: return makeColor(q, v, p); case 2: return makeColor(p, v, t); case 3: return makeColor(p, q, v); case 4: return makeColor(t, p, v); default: return makeColor(v, p, q); } } private Color makeColor(float r, float g, float b) { return new Color(r, g, b); } class Color { float r, g, b; public Color(float r, float g, float b) { super(); this.r = r * 256; this.g = g * 256; this.b = b * 256; } public Color() { super(); } public float getR() { return r; } public void setR(float r) { this.r = r; } public float getG() { return g; } public void setG(float g) { this.g = g; } public float getB() { return b; } public void setB(float b) { this.b = b; } } }