1

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; 
    }
}

2 Answers 2

1

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!

Sign up to request clarification or add additional context in comments.

2 Comments

It is a very bad idea to load the images in every frame! That will gain a performance impact but no fun.
@Rabbid76 you are absolutely right. I almost erased this answer reading your comment, but I'll let it stand exactly because of it: it's good to know that we shouldn't load the images all the times (although I'll edit it to reflect this clearly).
1

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);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.