Draw an amount of rectangles based on a variable

edited October 2016 in How To...

Hi all,

I have a problem with drawing an amount of rectangles on the screen.

I have a variable where i declare the amount of rectangles Processing should draw on the screen, for now it is set to 3. If i change it to 4 i would like the program to draw 4 rectangles, every rectangle should have the same margin in between. If i change it to 5, it should draw 5 and so on.

I might be able to do this with an if-else-if construction but than i have to declare all new positions every time for all amounts.

So my question is if there is a simpler way to do this? Can i let Processing calculate the space in between and width of the rectangles?

Any help will be appreciated :)

int amountOfRects = 3;
int rectWidth = 100;

void setup(){
  size(500,300);
}

void draw(){
  rect(rectWidth/2, 50, rectWidth, 200);
  rect(rectWidth+100, 50, rectWidth, 200);
  rect(rectWidth*3+50, 50, rectWidth, 200);
}
Tagged:

Answers

  • You could use a for loop.

    Shameless self-promotion: I wrote a tutorial on for loops in Processing available here.

    You could also check out the reference or do a google search for a ton of resources.

  • Answer ✓

    with n rectangles you have n * rectWidth plus n + 1 gaps.

    so your gap size is (width - (n * rectWidth)) / (n + 1)

    your 0th rectangle starts at gapSize and ends at gapSize + rectWidth

    your 1st rectangle starts at gapSize + rectWidth + gapSize

    in general your nth rectangle starts at gapsize + n * (rectWidth + gapSize)

    (i've assumed the gap is equally spread between rectangles and before and after)

    NB numbering starts at 0, like a for loop should.

  • I'm sure there's a cleaner way but this works:

    int rectNum = 4;
    int space = 10;
    
    void setup() {
      size(800, 400);
      rectMode(CENTER);
    }
    
    void draw() {
      background(255);
      int rectSize = ((width-((rectNum+1)*space))/rectNum);
    
      for (int i = 0; i < rectNum; i++) {
        rect((rectSize+space)*i+(rectSize/2+space), height/2, rectSize, height/3);
      }
    }
    
  • @KevinWorkman Thanks for your tutorial, you wrote it very well and pointed me in the right direction. I spend some time practising and i got it working.

    @koogs Your comment made me think about the construction of the for loop i had to use. Thanks to your comment i got it working as well

    @CharlesDesign Your code works as well, i have made it a bit different (without the space variable) but it motivates me to optimize my code.

    Thanks to all of you for helping me out! I have learned another thing today :)

Sign In or Register to comment.