Limit the translate to window extent.
in
Programming Questions
•
3 years ago
I have been working on this code that takes and image and let’s me zoom in using the scale() function tied to the mouse wheel. And, I can drag the image around the screen using the translate((width/2)+x, (height/2)+y) function with x & y being updated by the void mousePressed() and void mouseDragged(). So far the code works great but I would like to limit the amount I can translate the the image to the size of the screen.
So if the scale is “1.00” I can’t move the image at all and if the scale is 1.05 I can only move the image ((width*Scale)-width/2). My background is black and I never want to see it. I have tried adding an if statement in the void mouseDragged() function but it does not work well.
Any advice on how to do this, or could you point me at a forum or an example where this is already being done.
Code:
PImage sdsu;
PImage sdsu_key;
float Scale = 1;
float x = 0;
float y = 0;
float easing = 0.1;
float testx = 0;
float testy = 0;
float bdifx = 0;
float bdify = 0;
float targetX, targetY;
void setup() {
size(600, 450);
sdsu = loadImage("SDSU.png");
// enable the mouse wheel, for zooming
addMouseWheelListener(new java.awt.event.MouseWheelListener() {
public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
mouseWheel(evt.getWheelRotation());
}});
}
void draw(){
background(0);
smooth();
drawImage();
}
// zoom in or out:
void mouseWheel(int delta) {
if (delta < 0){
Scale *= 1.05;
}
else if ((delta > 0) && (Scale > 1.05)) {
Scale *= 1.0/1.05;
}
}
// draws the image
void drawImage() {
imageMode(CENTER);
translate((width/2)+ x, (height/2)+ y);
scale(Scale);
image(sdsu, 0, 0, width, height);
}
//
void mousePressed(){
targetX = mouseX;
targetY = mouseY;
bdifx = targetX - x;
bdify = targetY - y;
}
void mouseDragged(){
x = (mouseX - bdifx);
y = (mouseY - bdify);
}
void keyReleased(){
if (key == ' '){
Scale = 1;
x=0;
y=0;
}}
Code:
PImage sdsu;
PImage sdsu_key;
float Scale = 1;
float x = 0;
float y = 0;
float easing = 0.1;
float testx = 0;
float testy = 0;
float bdifx = 0;
float bdify = 0;
float targetX, targetY;
void setup() {
size(600, 450);
sdsu = loadImage("SDSU.png");
// enable the mouse wheel, for zooming
addMouseWheelListener(new java.awt.event.MouseWheelListener() {
public void mouseWheelMoved(java.awt.event.MouseWheelEvent evt) {
mouseWheel(evt.getWheelRotation());
}});
}
void draw(){
background(0);
smooth();
drawImage();
}
// zoom in or out:
void mouseWheel(int delta) {
if (delta < 0){
Scale *= 1.05;
}
else if ((delta > 0) && (Scale > 1.05)) {
Scale *= 1.0/1.05;
}
}
// draws the image
void drawImage() {
imageMode(CENTER);
translate((width/2)+ x, (height/2)+ y);
scale(Scale);
image(sdsu, 0, 0, width, height);
}
//
void mousePressed(){
targetX = mouseX;
targetY = mouseY;
bdifx = targetX - x;
bdify = targetY - y;
}
void mouseDragged(){
x = (mouseX - bdifx);
y = (mouseY - bdify);
}
void keyReleased(){
if (key == ' '){
Scale = 1;
x=0;
y=0;
}}
1