Change Image object size with mouse

Hi! I’m here again with the question.
I have an image object that I would like to display firstly small, but I want that when the user clicks and holds mouse pressed on the image and than starts to move mouse, the image should become bigger or smaller(depends on the direction of mouse). What I’ve firstly tried:
in mousePressed() function I added

if(mousePressed == true){
 img.width = stoneSize+mouseX;
 img.height = stoneSize+mouseY;}

but…well…I understand it is not right as I need the left down corner of the picture be at the position of mouseX,mouseY. And what do I do when the image is not square, but round?

I’m assuming that when u press and move the mouse left the image should increase and vice-versa
this might help

if(mousePressed == true){
  if((pmouseX-mouseX)>0){
    img.width = stoneSize+mouseX;
    img.height = stoneSize+mouseY;
   }
  else{
    img.width = stoneSize-mouseX;
    img.height = stoneSize-mouseY;
  }
 }
1 Like

this version uses a copy of the initial image every time to avoid the distortion of the image over time.

It doesn’t preserve aspect ratio.

(EDITED: new version)



// https://discourse.processing.org/t/change-image-object-size-with-mouse/27077

PImage img, imgOriginal; 

boolean drag=false; 
int startX, startY;

//------------------------------------------------------
// Two Core Funcs 

void setup() {
  size(1800, 800);

  img=loadImage("c1.png");
  img.resize(460, 0);
  imgOriginal=(PImage)img.copy();
}//func


void draw() {

  background(220);
  fill(0);
  text("Click, hold and drag mouse to change the image size.", 
    12, 12); 

  img=resizeWithMouse(imgOriginal.copy(), img); 
  image(img, 90, 90);
}//func

//------------------------------------------------------
// Input funcs

void mousePressed() {
  drag=true;
  startX=mouseX; 
  startY=mouseY;
}//func

void mouseReleased() {
  drag=false;
}//func

//-------------------------------------------------------
// Other funcs

PImage resizeWithMouse( PImage imgLocal, PImage imgLocal2) {
  int newW=0; 
  int newH=0;

  if (drag) {
    // It is drag 

    // ------
    if (mouseX>startX) {
      newW=imgLocal2.width+(mouseX-startX);
      startX=mouseX;
    } else {
      newW=imgLocal2.width-abs(mouseX-startX);
      startX=mouseX;
    }
    if (newW<=0) 
      newW=3; 

    // ------
    if (mouseY>startY) {
      newH=imgLocal2.height+(mouseY-startY);
      startY=mouseY;
    } else {
      newH=imgLocal2.height-abs(mouseY-startY);
      startY=mouseY;
    }
    if (newH<=0) 
      newH=3; 

    // --------------------------
    if (newW>0 && newH>0)
      imgLocal.resize(newW, newH);

    return imgLocal;
  }//if

  return imgLocal2;
}//func
//


1 Like

Thanks! Tried to use it in my code, wokrs good, just needs a little bit of polishing to fit in my program properly and I managed to keep ratio! I am very grateful!

1 Like