Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a Random Color Java [duplicate]

I am trying to create a random color by randomly generating numbers for R,G, and B values with a random number generator, and using the values to make a color. The following code is in my onCreate() method:

Random rand = new Random();
    // Java 'Color' class takes 3 floats, from 0 to 1.
    float r = rand.nextFloat();
    float g = rand.nextFloat();
    float b = rand.nextFloat();
    Color randomColor = new Color(r, g, b);

How come eclipse tells me "The constructor Color(float, float, float) is undefined"? Shouldn't this work correctly?

like image 419
ThatGuyThere Avatar asked Dec 13 '13 07:12

ThatGuyThere


People also ask

How do you randomize colors in Java?

Random rand = new Random(); As colours are separated into red green and blue, you can create a new random colour by creating random primary colours: // Java 'Color' class takes 3 floats, from 0 to 1. float r = rand.

How do you get random color flutters?

There is a random_color plugin in the Flutter that can help us for generating random color and also we can select high saturation colors with this code: import 'package:random_color/random_color. dart'; RandomColor _randomColor = RandomColor(); Color _color = _randomColor.


2 Answers

You should use nextInt(int n):int to generate a random integer between 0 and 255. (note that according to API the range is not checked within the Color methods so if you don't limit it yourself you'll end up with invalid color values)

// generate the random integers for r, g and b value
Random rand = new Random();
int r = rand.nextInt(255);
int g = rand.nextInt(255);
int b = rand.nextInt(255);

Then get an int color value with the static Color.rgb(r,g,b):int method. The only constructor that exists for android.graphics.Color is a non argument constructor.

int randomColor = Color.rgb(r,g,b);

Finally, as an example, use the setBackgroundColor(int c):void method to set a color background to a view.

View someView.setBackgroundColor(randomColor);
like image 62
hcpl Avatar answered Sep 24 '22 02:09

hcpl


public int randomColor(int alpha) {

    int r = (int) (0xff * Math.random());
    int g = (int) (0xff * Math.random());
    int b = (int) (0xff * Math.random());

    return Color.argb(alpha, r, g, b);
}

can it help?

like image 45
venciallee Avatar answered Sep 23 '22 02:09

venciallee