Question

I'm trying to get a random HSV colour then convert it to RGB to be used. Does anyone have any ideas as to how I can do this? Thanks, Sam. What I've got so far: First method converts HSV to RGB with the specified values, the second method is for getting a random colour.

public static float[] HSVtoRGB(float h, float s, float v) {
    float m, n, f;
    int i;

    float[] hsv = new float[3];
    float[] rgb = new float[3];

    hsv[0] = h;
    hsv[1] = s;
    hsv[2] = v;

    if (hsv[0] == -1) {
        rgb[0] = rgb[1] = rgb[2] = hsv[2];
        return rgb;
    }
    i = (int) (Math.floor(hsv[0]));
    f = hsv[0] - i;
    if (i % 2 == 0) {
        f = 1 - f; // if i is even
    }
    m = hsv[2] * (1 - hsv[1]);
    n = hsv[2] * (1 - hsv[1] * f);
    switch (i) {
        case 6:
        case 0:
            rgb[0] = hsv[2];
            rgb[1] = n;
            rgb[2] = m;
            break;
        case 1:
            rgb[0] = n;
            rgb[1] = hsv[2];
            rgb[2] = m;
            break;
        case 2:
            rgb[0] = m;
            rgb[1] = hsv[2];
            rgb[2] = n;
            break;
        case 3:
            rgb[0] = m;
            rgb[1] = n;
            rgb[2] = hsv[2];
            break;
        case 4:
            rgb[0] = n;
            rgb[1] = m;
            rgb[2] = hsv[2];
            break;
        case 5:
            rgb[0] = hsv[2];
            rgb[1] = m;
            rgb[2] = n;
            break;
    }
    return rgb;
}

public static int randomColor() {
    int hue = (int) (Math.random() * 6.0f);
    int saturation = (int) (Math.random());
    int brightness = (int) (Math.random());

    float[] rgb = HSVtoRGB(hue, saturation, brightness);

    int red = (int) (rgb[0] * 255.0f);
    int green = (int) (rgb[1] * 255.0f);
    int blue = (int) (rgb[2] * 255.0f);

    return (red << 16) | (green << 8) | blue;
}
Was it helpful?

Solution

You can use java.awt.Color.RGBtoHSB(...) You can find the relevant documentation for it here: http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/Color.html

Then it just becomes trivial of generating a random color.

int red = (int) (Math.random() * 256)
int green = (int) (Math.random() * 256)
int blue = (int) (Math.random() * 256)

Then convert directly. Note that there is also a HSBtoRGB(...) function in the same class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top