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?
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.
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.
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);
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With