使用随机类获取随机颜色?

时间:2015-05-05 08:12:42

标签: java android

我的应用程序的要求是listview项目的浅色但不透明的颜色。我得到随机颜色,但它经常很暗。而且我不知道我可以在哪个范围内获得浅色。随机给出的范围是这样的:

 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);

5 个答案:

答案 0 :(得分:5)

你想要更浅的颜色。这意味着RGB分量值必须介于128和255之间。

由于Random.nextInt(int max)返回int between 0 inclusive and max exclusive,您可能想尝试这样的事情:

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);

答案 1 :(得分:4)

我向你指了一个想法,我将在这里解释一下:

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();

请参阅?我正在创建一个虚拟Bitmap,用随机生成的颜色填充它,然后使用Palette API获得“明亮的”颜色。

答案 2 :(得分:4)

通常,您需要其中一个RGB值大于128才能获得明亮的颜色,因此拾取3个随机值,并检查一个大于128的值就足够了。值越大,它就越亮。

你可以检查平均值是否大于128,它可以带来好结果。

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);
}

答案 3 :(得分:3)

要获得明亮的随机颜色,您希望每个通道都具有一些最小值。

以下是代码:

Instantiate(tileChoice, randomPosition, Quaternion.identity);
lastRandomPos = randomPosition;

答案 4 :(得分:2)

在处理光线强度时(在您的情况下,您需要浅色),HSI model会派上用场。您可以随机生成0.8到1之间的强度,并随机化色调和饱和度。然后将其转换为RGB。