How to fill indivdual shapes with different colours in a for loop

I’m making a drawing program and I want a sidebar that shows the colour options. How would I make each rectangle a different colour if there in a for loop?

for (int j = 1; j<= 3; j++)
{
for (int i = 1; i<= 2; i++)
{
rect (i40-28, j70+30, 35, 35);
}
}

You can make a array of colors and then in the for loop increment an int variable as an index for it

example 1


color[] colorList = {

  color(0), // black 
  color(255), // white 

  // Red,Green,Blue 
  color(255, 0, 0), 
  color(0, 255, 0), 
  color(0, 0, 255), 

  // colors inbetween 1 (with 55)
  color(55, 255, 255), 
  color(255, 55, 255), 
  color(255, 255, 55), 

  // colors inbetween 2 (with 0)
  color(0, 255, 255), 
  color(255, 0, 255), 
  color(255, 255, 0)
};

void setup() {
  size(1100, 600);
  background(111);
}//func 

void draw() {

  final int sizeRect=70; // size of one rectangle 
  int x=20;  //  x position 

  // loop over all colors
  for (color currentColor : colorList) {
    // display rect with that color
    fill(currentColor); 
    rect(x, 100, sizeRect, sizeRect);

    // increment x position 
    x+=sizeRect+10;
  }//for
}//func 
//

and for your code




color[] colorList = {

  color(0), // black 
  color(255), // white 

  // Red,Green,Blue 
  color(255, 0, 0), 
  color(0, 255, 0), 
  color(0, 0, 255), 

  // colors inbetween 1 (with 55)
  color(55, 255, 255), 
  color(255, 55, 255), 
  color(255, 255, 55), 

  // colors inbetween 2 (with 0)
  color(0, 255, 255), 
  color(255, 0, 255), 
  color(255, 255, 0)
};

void setup() {
  size(1100, 600);
  background(111);
}//func 

void draw() {

  int k=0; 

  // loop over all colors
  for (int j = 1; j <= 3; j++)
  {
    for (int i = 1; i <= 2; i++)
    {
      fill(colorList[k%11]); 
      rect (i*40-28, j*70+30, 
        35, 35);
      k++;
    }
  }
}//func 
//

1 Like

Hi Doug,

Indeed. What @Chrisir said probably makes the most sense. However, because it is Christmas, and I was looking for something to do, here’s an example that generates swatch colours off the HSB wheel:


int numSwatchesX = 12;
int numSwatchesY = 3;

int marginX = 50;
int marginY = 50;

int swatchSize = 40;
int swatchSpacing = 5;


void setup()
{
  size(800, 800);

  for(int i = 0; i < numSwatchesX; i++)
  {
    for(int j = 0; j < numSwatchesY; j++)
    {
      float alignBottom = height - (marginY + (swatchSize+swatchSpacing) * numSwatchesY);
      
      float swatchX = marginX + i * (swatchSize+swatchSpacing);
      float swatchY = alignBottom + j * (swatchSize+swatchSpacing);
      
      colorMode(HSB, 360, 255, 255);
      fill(360.f / numSwatchesX * i, 255, 255 - j * (255 / numSwatchesY));
      rect(swatchX, swatchY, swatchSize, swatchSize);
    }
  }

}
  
2 Likes

thank you very much. Happy holidays

1 Like

I added 2 examples to my initial post

Happy holidays!