pB2556
pB2556

Reputation: 77

How can i make an output of multiple images with an for loop in processing?

I am making a programm that should display 10 images next to each other with the loadImages(int i) function and the output to that is in the void setup() function , but the problem is it only loads up the 10th picture and not the others before that (1-9). I know it is probably only a minor modification to the code but i dont get it. Thanks in advance!

import java.util.Random;
Random Random = new Random(); 
PImage img;
int[] cakes = new int[10];
int W, H;

void setup() {
    for( int i=0 ;i<=cakes.length;i++){  
        img =loadImages(i);
    }
    W = img.width;
    H = img.height;
    surface.setSize(10 * W, 2 * H); 
}

void mouseClicked() {
    scramble(cakes);
} 

PImage loadImages(int i) {
    return loadImage("images/" + i + "_128x128.png");
}

void draw() {
    background(255);
    image(img, 0, 0); 
}

void scramble(int[] a) {
    for (int i = 0; i < a.length; i++) {
        int rd0 = Random.nextInt(i+1);
        int rd1 = Random.nextInt(i+1);
        int temp = a[rd0]; 
        a[rd0] = a[rd1]; 
        a[rd1] = temp; 
    }
}

Upvotes: 1

Views: 855

Answers (2)

laancelot
laancelot

Reputation: 3207

EDIT: as pointed out by @Rabbid76, it would be MUCH BETTER to avoid loading the image at every iteration of the draw loop. Consider this carefully.

You can get your images in a loop. As you guessed, it's only a minor modification:

void draw() {
  background(255);
  for (int i = 0; i < 10; i++) {
    image(loadImages(i), i*128, 0); // i * 128 to draw the image side by side, or else you'll only see the last one you draw
  }
}

Have fun!

Upvotes: 1

Rabbid76
Rabbid76

Reputation: 210876

You've to create an array of images:

PImage[] img = new PImage[10];

Load the images to the array:

void setup() {
    for( int i=0 ;i<img .length;i++){  
       img[i] = loadImages(i);
    }

    // [...]
}

Finally draw the array of images. e.g.:

void draw() {
    background(255);
    for( int i=0 ;i < img.length; i++){ 
        image(img[i], i*W, 0);
    }
}

Upvotes: 1

Related Questions