How to find cellsize in 4 * 4 grid of canvas size 1280*720?

I have been trying to execute a program where I will insert images in each cell. Considering it is a 4 * 4 grid, each cell size would be 360*180. How do I represent that in equation?

Whenever I implement the following code I get this result ( I don't want the gapes and not bleed off at the borders. What am i doing wrong?

Following is the code:-

PImage[] pieces=new PImage[16];

void setup() {
  size(1280, 720);
  for (int i=1; i<pieces.length; i++) {

void draw() {
  float gridsize=4;

  float cellsize=(width/4); //calculating the cellsize to insert images in it

  for (int i=0; i<gridsize; i++) {
    for (int j=0; j<gridsize; j++) {

      int index=int(random(1, pieces.length));
      image(pieces[index], i*cellsize, j*cellsize);


  • edited September 2016 Answer ✓

    You are using cellsize for both width and height of your cells. Either write 2*cellsize for the width or declare a new variable. You should also check the image dimensions to fit inside the cells

  • edited September 2016 Answer ✓

    To echo Alex_Pr, your code will be even clearer if instead of cellsize you create one variable cellwidth and a second variable cellheight. You might also want to consider changing gridsize to gridwidth and gridheight -- they can each be 4 and 4, but if you decide to later make your layout 4x3 or 3*8 then coding the grid units for height and width separately makes this easy to change.

  • edited September 2016

    @jeremydouglas Thanks, your answer was really helpful.

Sign In or Register to comment.