"zoom" into image based on window center only

Hello everyone!

I am trying to create the effect of zooming in on an image based on the center of the program window, NOT based on the center of an image whose mode has been set to CENTER.

The code below shows what happens when I resize to zoom, but if it did what I wanted you could then zoom in on whatever is in the center of program window. You see, the complete version of this code allows you to drag the image around and zoom in when clicked. I’ve tried various ways to offset the shift that occurs as the image stretches in all directions, to no avail. I’m pretty sure the key is using translate…

I hope this makes sense, an tips would be appreciated. Thank you in advance!

int x = 110;
int y = 150;
int w = 250;
int h = 150;

PImage map;

void setup(){
    size(300, 300);    
    map = loadImage("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2e/Processing_3_logo.png/480px-Processing_3_logo.png");  
}

void draw(){
  
    background(255);
  
    rectMode(CENTER);
    
    //window
    fill(0,0,100,75);
    rect(width/2,height/2,200,100);
    fill(0,255,0,50);
    rect(width/2,height/2,8,8);
    
    //image   
    imageMode(CENTER);
    tint(255, 127);
    image(map,x,y,w,h);    

    if(keyPressed && key == 'a'){
      w = w+10;
      h = h+10;
    }
    
    if(keyPressed && key == 's'){
      w = w-10;
      h = h-10;
    }
    
}
1 Like

Have you tried/played with scale() ?

Use the ratio of new / old width and height, and multiply this with the horizontal and vertical distance (each separately). Or some such variant depending on how image() arguments works, but that seems to do the trick.

Also, use floats for the x,y,w,h variables.

I’m just going to post it:

float x = 110;
float y = 150;
float w = 250;
float h = 150;

PImage map;

void setup(){
    size(300, 300);
    map = loadImage("480px-Processing_3_logo.png");  
}

void draw(){
  
    background(255);
  
    rectMode(CENTER);
    
    //window
    fill(0,0,100,75);
    rect(width/2,height/2,200,100);
    fill(0,255,0,50);
    rect(width/2,height/2,8,8);
    
    //image   
    imageMode(CENTER);
    tint(255, 127);
    image(map,x,y,w,h);    

    if(keyPressed && key == 'a'){
      w = w+10;
      h = h+10;
      float xRatio = w/(w-10);
      float yRatio = h/(h-10);
      x = ((x-width/2)*xRatio)+width/2;
      y = ((y-height/2)*yRatio)+height/2;
    }
    
    if(keyPressed && key == 's'){
      w = w-10;
      h = h-10;
      float xRatio = w/(w+10);
      float yRatio = h/(h+10);
      x = ((x-width/2)*xRatio)+width/2;
      y = ((y-height/2)*yRatio)+height/2;
    }
    
}

2 Likes

Aha, I WAS close!

Thank you very much raron, that did it.

And the reason I am not using scale or resize is because I’m working with a lot of very large images to make an animation and those techniques would be too slow.

2 Likes