We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello!
I'm working with an image and it is able to be panned and zoomed so far, using mouse dragging to pan and keys to zoom. What I am trying to do now is set a constrain on the image, so that it cannot be panned offscreen. I don't want the background to ever be visible, basically, so when the image is not zoomed, it shouldn't move.
I've tried using the constrain() tool but haven't been able to make it work so far.
Here is the code where the panning and zooming takes place:
PImage campus; //this is a 650 by 450 image
int imgX = 0;
int imgY = 0;
int imgW = 0;
int imgH = 0;
int panFromX = 0;
int panFromY = 0;
int panToX = 0;
int panToY = 0;
float scaler = 1;
void setup() {
size(800, 450); //there is white space on the side for buttons
background(255);
campus = loadImage("mkmap.png");
imgW = campus.width;
imgH = campus.height;
}
void draw() {
background(255);
pushMatrix();
translate(imgW/2, imgH/2);
scale(scaler);
translate(-imgW/2, -imgH/2);
image(campus, imgX, imgY, imgW, imgH);
popMatrix();
}
void mousePressed() {
panFromX = mouseX;
panFromY = mouseY;
}
void mouseDragged() {
panToX = mouseX;
panToY = mouseY;
int xShift = panToX - panFromX;
int yShift = panToY - panFromY;
imgX = imgX + xShift;
imgY = imgY + yShift;
panFromX = panToX;
panFromY = panToY;
}
void keyPressed() {
if (key == 'x') {
scaler -= 0.1;
}
if (key == 'z') {
scaler += 0.1;
}
if (key == 'c') {
scaler = 1;
}
}
Thanks so much for your time and help!
Answers
Having a full self-contained example we can run would help people in trying to help you, by experimenting... Not your full code, just a minimal code reproducing your issue.
Added the rest!
If you add the following at the end of mouseDragged(), it constraints the image when the scale is 1.
You have to use the scale to adjust the limits, in other cases.
Simpler with Processing's function:
B-)
is close when we up-scale.