Drag & move image inside window ! [solved]

Hi all.

I have a image 300x300 and my draw code is :

  
  
ofPoint imgPos;  
ofPoint dist;  
ofImage img;  
int w, h;  
  
void testApp::setup(){  
    img.loadImage("img.png");  
    w = img.width;  
    h = img.height;  
    imgPos.x = (ofGetWidth()-w)/2;  
    imgPos.y = (ofGetHeight()-h)/2;  
}  
  
void testApp::draw(){  
    img.draw(imgPos.x, imgPos.y, w,h);  
}  
  
void testApp::mousePressed(int x, int y, int button){  
    dist.x = mouseX - imgPos.x;  
    dist.y = mouseY - imgPos.y;  
}  
  
void testApp::mouseDragged(int x, int y, int button){  
    imgPos.x = mouseX - dist.x;  
    imgPos.y = mouseY - dist.y;  
}  
  
  

I want the edge of image don’t leave the window, I mean to move the image only inside window.

Thanks.

in your update code, apply a boundry check for the image.

  
    if(imgPos.x >= ofGetWindowWidth()-img.width)  
    {  
        imgPos.x = ofGetWindowWidth()-img.width;  
    }  
    if(imgPos.x <= 0)  
    {  
        imgPos.x = 0;  
    }  

etc etc etc

1 Like

@Syrou thank you man… it worked :slight_smile:

No problem, at a later point you probably want to start thinking about having the anchorpoint of the image in the middle of it.

And then it would looke something like this:

  
void testApp::update()  
{  
    //Check width  
    if(imgPos.x >= ofGetWindowWidth()-img.width/2)  
    {  
        imgPos.x = ofGetWindowWidth()-img.width/2;  
    }  
    if(imgPos.x <= img.width/2)  
    {  
        imgPos.x = img.width/2;  
    }  
    //Check height  
    if(imgPos.y >= ofGetWindowHeight()-img.height/2)  
    {  
        imgPos.y = ofGetWindowHeight()-img.height/2;  
    }  
    if(imgPos.y <= img.height/2)  
    {  
        imgPos.y = img.height/2;  
    }  
}  
  
//--------------------------------------------------------------  
void testApp::draw()  
{  
    img.setAnchorPercent(0.5, 0.5);   
    img.draw(imgPos.x, imgPos.y, w,h);  
}  

1 Like

@Syrou you save my day man :slight_smile: thank you again…!