Search code examples
javaarrayssortingprocessing

display array sorted


Suppose I have a two-dimensional grid of pixels (4 by 4 pixels) - and I have an image the size of my sketch that has been cut into 16 parts. Now I load all 16 parts into an array. I want to map this array onto the 2D grid in turn, so that my overall image is put together again correctly. That is, top left image 0.png and bottom right image 16.png.

I just can't find the formula that allows me to do this. For example, I know that with x+y*width you can run trough all pixels – from top left to bottom right - so I tried that. Without *width it doesn't sit together properly - with x+y*width- ArrayIndexOutOfBoundsException (for sure).

So I thought I needed a 2D array - but with images[x][y] i get a NullPointerException. I attached you an image of what I am trying to create:

the grid with the sliced images – 16

This is my code so far – without the 2D Array…

float pixelamount = 4;
float pixelsize;

PImage[] images = new PImage [16];

void setup() {
  size(1080, 1080);
  pixelsize = width/pixelamount;
  for (int i = 0; i < images.length; i++) {
    images[i] = loadImage(i + ".png");
  }
  imageMode(CENTER);
}

void draw() {
  background(0);
  pushMatrix();
  translate(pixelsize/2, pixelsize/2);
  for (int x = 0; x < pixelamount; x++) {
    for (int y = 0; y < pixelamount; y++) {
      pushMatrix();
      translate(pixelsize*x, pixelsize*y);
      image(images[x+y], 0, 0, pixelsize, pixelsize);
      popMatrix();
    }
  }
  popMatrix();
}

As I said – in the line image(images[x+y], 0, 0, pixelsize, pixelsize); I just do not get the math right. Do I need a 2D Array to solve this? Or something totally different?


Solution

  • This should be resolved without 2D array.

    If the dimensions of the field are known 4x4, then possibly the loop should run from 0 to 4 something like this:

    void draw() {
      background(0);
      pushMatrix();
      translate(pixelsize/2, pixelsize/2);
      for (int x = 0; x < 4; x++) {
        for (int y = 0; y < 4; y++) {
          pushMatrix();
          translate(pixelsize * x, pixelsize * y);
          image(images[4 * x + y], 0, 0, pixelsize, pixelsize);
          popMatrix();
        }
      }
      popMatrix();
    }