Android:点击生成随机颜色?

115

我有一个ImageView,在其中我以编程方式创建可绘制对象并向用户呈现它们。我的目标是点击该ImageView并更改可绘制对象的颜色。

我要如何实现随机颜色更改?我目前正在尝试使用Random()Color.argb()和其他一些东西,但似乎无法使其正常工作!

17个回答

371
Random rnd = new Random();
paint.setARGB(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
或者
Random rnd = new Random(); 
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));   
view.setBackgroundColor(color);

尽管在你的情况下,似乎你想创建一个新的drawable并将其分配给你的视图。实际上,在你的情况下,这个drawable是什么?它是一张图片、形状、填充......


16
所有地方都应该是256而不是255吗?nextInt()的API说明是“返回一个半开区间[0, n)中均匀分布的伪随机int”。 - Catalin Morosan
1
Kaciula,你是对的,n被排除在外:http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Random.html - Lumis
int color = 0xFF000000 | rnd.nextInt(0xFFFFFF); "只使用一个随机数而不是三个" - Umesh Chhabra
Color.argb函数需要至少API 26才能正常工作。 - That's Enam
2
@That'sEnam 不对,有两个Color.argb函数,一个接受int参数,自API级别1就存在了,你所说的那个接受float参数的函数是从API 26才开始存在的。 - Shane Monks O'Byrne

21
如果你正在寻找一个美丽的色彩调色板,也许使用完全随机的值并不是一个好主意。 这种方法可能不会产生最好的结果,它总是会得到一系列过于暗或过于亮的相似颜色。
半随机方法(Java):
如果你需要一些新鲜而闪亮的颜色,可以使用以下简单的类,我之前在遇到相同问题时写过。它是半随机的,并使用预定义的色彩调色板:
class RandomColors {
    private Stack<Integer> recycle, colors;

    public RandomColors() {
        colors = new Stack<>();
        recycle =new Stack<>();
        recycle.addAll(Arrays.asList(
                0xfff44336,0xffe91e63,0xff9c27b0,0xff673ab7,
                0xff3f51b5,0xff2196f3,0xff03a9f4,0xff00bcd4,
                0xff009688,0xff4caf50,0xff8bc34a,0xffcddc39,
                0xffffeb3b,0xffffc107,0xffff9800,0xffff5722,
                0xff795548,0xff9e9e9e,0xff607d8b,0xff333333
                )
        );
    }

    public int getColor() {
        if (colors.size()==0) {
            while(!recycle.isEmpty())
                colors.push(recycle.pop());
            Collections.shuffle(colors);
        }
        Integer c= colors.pop();
        recycle.push(c);
        return c;
    }
}

Random Color Generator class for android


随机方法(Java):

但是如果你仍然考虑使用随机方法,你可能希望使用这一行代码而不是多行代码:

int color= ((int)(Math.random()*16777215)) | (0xFF << 24);

Random Color Generator android

使用(0xFF << 24)的目的是将alpha值设置为最大值,即完全不透明。

半随机(Kotlin)

class RandomColors() {
    private val recycle:Stack<Int> = Stack()
    private val colors:Stack<Int> = Stack()
    init {
        recycle.addAll(
            Arrays.asList(
                // ARGB hex to int >> (0xFFEE5670.toInt(),...)
                -0xbbcca, -0x16e19d, -0x63d850, -0x98c549,  
                -0xc0ae4b, -0xde690d, -0xfc560c, -0xff432c,
                -0xff6978, -0xb350b0, -0x743cb6, -0x3223c7,
                -0x14c5, -0x3ef9, -0x6800, -0xa8de,
                -0x86aab8, -0x616162, -0x9f8275, -0xcccccd
            )
        )
    }

    fun getColor(): Int {
        if (colors.size == 0)
            while (!recycle.isEmpty()) colors.push(recycle.pop())
            Collections.shuffle(colors)
        val c = colors.pop()
        recycle.push(c)
        return c
    }
}

随机方法(Kotlin):

val color = (Math.random() * 16777215).toInt() or (0xFF shl 24)

随机方法(组合):

fun randomColor(alpha:Int=255) = Color(
    Random.nextInt(256),
    Random.nextInt(256),
    Random.nextInt(256),
    alpha = alpha)

优先地
val randomColor
    get() = Color(Random.nextInt(256), Random.nextInt(256), Random.nextInt(256))

1
你的设计案例是最好的控制案例;-) - JWL

20

要获取随机颜色值,您可以使用以下方法:

public int getRandomColor(){
   Random rnd = new Random();
   return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
}

然后将其应用于您的观点:

myView.setBackgroundColor(getRandomColor());

enter image description here


8
在 Kotlin 中:
val rnd = Random()
val color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256))
myView.setBackgroundColor(color)

4
请确保从 java.util 导入 Random。 - YTerle

5
thing.setBackgroundColor(new Random().nextInt());

5
我遇到了这个问题,以下是我的代码,请帮忙看看。可能需要一些帮助。
 /**
 * view-source:http://www.kareno.org/js/colors/ 参考
 *Get Random background color and the text color for the background
 * @return 0--》background
 *          1--》text color
 */
public static  int[] getRandomColor() {
    Random random = new Random();
    int RGB = 0xff + 1;
    int[] colors = new int[2];
    int a = 256;
    int r1 = (int) Math.floor(Math.random() * RGB);
    int r2 = (int) Math.floor(Math.random() * RGB);
    int r3 = (int) Math.floor(Math.random() * RGB);
    colors[0] = Color.rgb(r1, r2, r3);
    if((r1 + r2 + r3) > 450) {
        colors[1] = Color.parseColor("#222222");
    }else{
        colors[1] = Color.parseColor("#ffffff");
    }
    return colors;
}

RGB 方法在哪里? - Rachit Mishra
@twntee rgb 是一个静态方法,请参见:[http://developer.android.com/reference/android/graphics/Color.html#rgb(int, int, int)]。 - Kevin
好的,我明白了!实际上,我的文件中有多个具有相同名称的导入。 - Rachit Mishra

3

这里有一个可以做同样事情的扩展程序:

fun Int.Companion.randomColor(): Int
{
    return Color.argb(255,
                      Random.nextInt(256),
                      Random.nextInt(256),
                      Random.nextInt(256))
}

以下是使用方法:

myTextView.setBackgroundColor(Int.randomColor());

3

你可以使用ColorGenerator来选择随机颜色

ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT

int color1 = generator.getRandomColor();      // generate random color

如果您想在重复的同一用户名上使用相同的特定颜色代码,可以像下面这样使用:

public int getColorCode(String userName)
    {
        ColorGenerator generator = ColorGenerator.MATERIAL; // or use DEFAULT
        // generate color based on a key (same key returns the same color), useful for list/grid views
        int colorCode = generator.getColor(userName);

        return colorCode;
    }

ColorGenerator是哪个库的? - Brill Pappin
它默认在Android包中可用。 - King of Masses
它不在当前的安卓版本中,也不在Material3库中。 - Brill Pappin

2

最简单的解决方案是改变范围以避免暗色或浅色,例如将范围改为30到200以避免黑色和白色系列。

val randomColor: Int
    get() {
        return Color.rgb((30..200).random(),(30..200).random(),(30..200).random())
    }

1
随机颜色在Jetpack Compose中的应用。
val RandomColor
    get() = Color(Random.nextInt(256), Random.nextInt(256), Random.nextInt(256))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接