Tint() in for loop doesn't work

Hi, I have this code that doesn’t work, why?

PImage img;

void setup() {
  size(400, 300);
  img= loadImage("myimage.jpg");
  image(img,0,0,width, height); 
}
 
void draw() {
 
}


float transparency = 255;
void keyPressed() {
      for (transparency=255;transparency>0;transparency = transparency-1){
      delay(10); 
      println(transparency);// entered to check: this works 
      image(img,0,0,width, height);      
      tint(255, transparency);// this does not work, why?
      }
}`Preformatted text`

Hi @Andry,

First, Please format your code. This makes use easier to help you. :slight_smile:

What is your expectation of what this code should do?

Cheers
— mnse

sorry for the incorrect formatting, hope i have solved

Unfortunately not

Reformat existing code:

  1. Click the edit (pencil) icon under an old post
  2. Highlight code
  3. On the editor header bar, press the </> code button (context name: Preformatted text) …or press Ctrl+Shift+c.

Done, thanks, it should be fine now.

The code should produce an animated fade on the image, but this is not the case.

Hi,

This won’t work that way…

The keypressed event is handled at once, so your image is currently painted from opaque (255) to transparent (0) all at the same time.
Also use the tint before drawing the image.

Check here and see what happend…

Cheers
— mnse

PImage img;
int transparency=0;

void setup() {
  size(400, 300);
  img= loadImage("myimage.jpg");
  // image(img,0,0,width, height); // useless
}
 
void draw() {
  background(0);
  tint(255, transparency);
  image(img,0,0,width, height);      
  transparency=(transparency+1) % 255;
}

Thanks, you were kind enough to answer me. Your code works, but I wanted it to work in a for loop, but if that’s not possible I’ll find an adaptation. Good day

I would recommend to reconsider your approach … a for loop imho just makes no sense in this concrete constellation… :slight_smile:

you can imagine the sketch as

for (frameCount = 0; as_Long_Sketch_Is_Running_And_No_Noloop_used;frameCount++) {
   // do things to prepare next draw call and call it
   draw();
}

or

while (as_Long_Sketch_Is_Running_And_No_Noloop_used) {
   // do things to prepare next draw call and call it
   draw();
}

But sure, you can do whatever you want in your coding … :wink:

Cheers
— mnse

Thanks this is a good solution. Good boy

Hello,

This tutorial discusses Events and Event flow:

:)