Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Random color using Random Class?

Tags:

java

android

My app's requirement is a light but not transparent color for the listview items. I am getting random colors, but it is very dark oftenly. And I don't know in which range can I get light colors only. The range given randomly is like this:

 Random rndm = new Random();
 int color = Color.argb(255, rndm.nextInt(256), rndm.nextInt(256), rndm.nextInt(256));
 RelativeLayout rl=(RelativeLayout)rowView.findViewById(R.id.front);
 rl.setBackgroundColor(color);
like image 337
Devendra Singh Avatar asked May 05 '15 08:05

Devendra Singh


3 Answers

You want lighter colors. This means the RGB components values must be between 128 and to 255.

Since Random.nextInt(int max) returns an int between 0 inclusive and max exclusive, you may want to try something like this:

Random rnd = new Random();
int r = rnd.nextInt(128) + 128; // 128 ... 255
int g = rnd.nextInt(128) + 128; // 128 ... 255
int b = rnd.nextInt(128) + 128; // 128 ... 255

Color clr = Color.rgb(r, g, b);
like image 168
Phantômaxx Avatar answered Oct 24 '22 12:10

Phantômaxx


I was pointing an idea to you, which I'll explain here:

Random random = new Random();
int color = Color.argb(255, random.nextInt(256), random.nextInt(256), random.nextInt(256));

Bitmap bitmap = new Bitmap(context);
bitmap.eraseColor(color);

Palette.from(bitmap).getLightVibrantColor();

See? I'm creating a dummy Bitmap, fill it with your randomly generated color, then using Palette API to get a "light vibrant" color.

like image 20
shkschneider Avatar answered Oct 24 '22 11:10

shkschneider


Generally you need one of the RGB values being are greater than 128 for getting a bright color, so picking up 3 random values, and checking for one to be greater than 128 could be enough. The greater the value, the brighter it will be.

You can check for the average to be greater than 128, it can bring a good result.

public int getRandomColor() {

Random rndm = new Random();

int r = rndm.nextInt(256);
int g = rndm.nextInt(256);
int b = rndm.nextInt(256);
int adjust = 0;

if( (r + g + b)/3 < 128)
    int adjust = (128 - (r + g + b)/3)/3;

r += adjust;
g += adjust;
b += adjust;

return Color.argb(255, r, g, b);
}
like image 4
Bowsska Avatar answered Oct 24 '22 13:10

Bowsska