如何给图片资源随机添加不同的颜色

how to add different colors to the Image resource randomly

我有一个圆形图像视图

circleImageView.setImageResource(R.color.colorPrimary);

我想添加随机颜色而不是 colorPrimary

我有一个数组

arraystring = {R.color.colorPrimary,R.color.blue,R.color.red}

我用随机函数的方法分配

String randomStr = arraystring [new Random().nextInt(array.length)];

但我不能给

circleImageView.setImageResource(randomStr);

他们还有其他方法可以给吗,请大家推荐一下

您应该改为传递 Int,因此创建一个方法 return @DrawableRes Int 然后使用 Random 从该数组中选取一个随机整数

先声明数组为整型数组

int[] colors = new int[] {R.color.colorPrimary,R.color.blue,R.color.red};

从整数数组中随机选择

int randomColor = colors[new Random().nextInt(colors.length)];

最后设置ImageView的颜色如下

circleImageView.setImageDrawable(new ColorDrawable(randomColor));

希望这对您有所帮助..

您需要在 color.xml 中添加颜色数组并将它们引用到 java 中的 int[] 代码,例如

int[] colors=context.getResources().getIntArray(R.array.borders);
    int randomColor=colors[new Random().nextInt(colors.length)];
         circularImageView.setBackgroundColor(randomColor);