Java Random Color randomColor(int idx)

Here you can find the source of randomColor(int idx)

Description

Port of DChip function of the same name.

License

LGPL

Parameter

Parameter Description
idx a parameter

Declaration

public static Color randomColor(int idx) 

Method Source Code

//package com.java2s;
/*//from   w ww.  j  a  va  2  s  .c  o m
 * Copyright (c) 2007-2012 The Broad Institute, Inc.
 * SOFTWARE COPYRIGHT NOTICE
 * This software and its documentation are the copyright of the Broad Institute, Inc. All rights are reserved.
 *
 * This software is supplied without any warranty or guaranteed support whatsoever. The Broad Institute is not responsible for its use, misuse, or functionality.
 *
 * This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
 * Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
 */

import java.awt.*;

public class Main {
    /**
     * Port of DChip function of the same name.
     * Calls {@link #randomColor(int, float)} with {@code alpha=1.0}
     *
     * @param idx
     * @return
     */
    public static Color randomColor(int idx) {
        return randomColor(idx, 1.0f);
    }

    /**
     * Generate a color based on {@code idx}. Unpredictable but deterministic (like a hash)
     * Good for generating a set of colors for successive values of {@code idx}.
     * Alpha value is set as specified
     *
     * @param idx
     * @param alpha alpha value of color, from 0.0-1.0
     * @return
     */
    public static Color randomColor(int idx, float alpha) {

        int[] rgb = quasiRandomColor(idx);

        int r = rgb[0];
        int g = rgb[1];
        int b = rgb[2];

        // Reject colors too close to white
        if (r > 200 && g > 200 && b > 200) {
            int tmp = r % 3;
            if (tmp == 0) {
                r = 255 - r;
            } else if (tmp == 1) {
                g = 255 - g;
            } else {
                b = 255 - b;
            }
        }
        return new Color(r, g, b, (int) (255 * alpha));
    }

    /**
     * @param idx
     * @return
     * @see #randomColor(int, float)
     */
    private static int[] quasiRandomColor(int idx) {
        int BASE_COL = 40;
        int RAND_COL = 255 - BASE_COL;

        idx += 1; // avoid 0
        int r = Math.abs(BASE_COL + (idx * 33) % RAND_COL);
        int g = Math.abs(BASE_COL + (idx * 55) % RAND_COL);
        int b = Math.abs(BASE_COL + (idx * 77) % RAND_COL);

        return new int[] { r, g, b };
    }
}

Related

  1. randomColor()
  2. randomColor()
  3. randomColor()
  4. randomColor()
  5. randomColor()
  6. randomColor(int seed)
  7. randomColor(Random r)
  8. randomColorFactor()
  9. randomColorValue()