Paint with random colors

2

I have the following onDraw :

public void onDraw(Canvas canvas) {
    paint = new Paint();
    paint.setColor(Color.RED);
    canvas.drawRect(rectangulo,paint);
}

I would like to know how to implement so that it was not just Color.RED , but random colors.

Something like an array with several colors and the color set calls it?

This is my code:

private static final int[] colores = {Color.GREEN,Color.BLUE,Color.RED};

In the constructor:

r = new Random();
num = r.nextInt(3);

and the Ondraw:

public void onDraw(Canvas canvas) {
  paint = new Paint();
  paint.setColor(colores[num]);
  canvas.drawRect(rectangulo,paint);
}
    
asked by PiledroMurcia 05.05.2017 в 10:06
source

2 answers

1

For that you can use this method:

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

What is used in this example: Android buttons . To call the method, you simply do it this way:

public void onDraw(Canvas canvas) {
    paint = new Paint();
    paint.setColor(getRandomColor()); //Asigna un color aleatorio.
    canvas.drawRect(rectangulo,paint);
}

so that each time the onDraw() method is called, paint a random color.

    
answered by 05.05.2017 / 16:18
source
2

The simplest for random colors is:

new Color((int)(Math.random() * 0x1000000))

Staying your method:

public void onDraw(Canvas canvas) {
    paint = new Paint();
    paint.setColor(new Color((int)(Math.random() * 0x1000000)));
    canvas.drawRect(rectangulo,paint);
}

Demo

Another way is to create each value of RGB individually.

public void onDraw(Canvas canvas) {
    Random r = new Random();
    Color randomColor = new Color( r.nextInt(256), r.nextInt(256), r.nextInt(256) );
    paint = new Paint();
    paint.setColor(randomColor);
    canvas.drawRect(rectangulo,paint);
}

Demo

Note: You have to import java.util.Random

    
answered by 05.05.2017 в 10:11