Then it would probably be best just not to make the zooming relative to the mouse, but relative to the center of the window instead.
So, instead of adding mouseX
and mouseY
to translateX
and translateY
, add width / 2
and height / 2
. Also, to limit your zooming, introduce the variables ZOOM_MN
and ZOOM_MAX
and set them to whatever value you like:
final float ZOOM_MIN = 0.2, ZOOM_MAX = 5;
Finally, perform some tests in mouseWheel
to see if the user has zoomed out to far. This is how the method should look like:
void mouseWheel(MouseEvent e) {
float p = -e.getCount()/10.0;
if (p < 0) {
if (scale <= ZOOM_MIN)
return;
} else if (scale >= ZOOM_MAX)
return;
float delta = pow(2, p), w = width /2, h = height / 2;
translateX -= w;
translateY -= h;
scale *= delta;
translateX *= delta;
translateY *= delta;
translateX += w;
translateY += h;
}