Created
January 30, 2019 22:27
-
-
Save kylemcdonald/8041f5ee88812dc669965632a3a130bf to your computer and use it in GitHub Desktop.
2D Zoomable Region for openFrameworks. Right click and drag to zoom. Left click and drag to translate.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include "ofMain.h" | |
class ZoomableRegion2D { | |
private: | |
float speed = 5; | |
float zoom = 1; | |
ofVec2f offset, startOffset, startDrag; | |
float startZoom; | |
float width, height; | |
public: | |
ZoomableRegion2D() { | |
ofAddListener(ofEvents().mouseDragged , this, &ZoomableRegion2D::mouseDragged); | |
ofAddListener(ofEvents().mousePressed, this, &ZoomableRegion2D::mousePressed); | |
} | |
ofVec2f unapply(ofVec2f x) { | |
return (x / zoom) - offset; | |
} | |
void begin(float width, float height) { | |
this->width = width, this->height = height; | |
float x = ofGetMouseX(); | |
ofPushMatrix(); | |
ofScale(zoom, zoom); | |
ofTranslate(offset); | |
} | |
void end() { | |
ofPopMatrix(); | |
} | |
void mouseDragged(ofMouseEventArgs& args) { | |
ofVec2f diff = args - startDrag; | |
offset = startOffset; | |
if(args.button == OF_MOUSE_BUTTON_RIGHT) { | |
zoom = startZoom * (1 + (exp((speed * diff.y) / height) - 1)); | |
zoom = MAX(zoom, 1); | |
offset -= (startDrag) * (1 - startZoom) / startZoom; | |
offset += (startDrag) * (1 - zoom) / zoom; | |
} else { | |
offset += diff / zoom; | |
} | |
offset.x = ofClamp(offset.x, width * (1 - zoom) / zoom, 0); | |
offset.y = ofClamp(offset.y, height * (1 - zoom) / zoom, 0); | |
} | |
void mousePressed(ofMouseEventArgs& args) { | |
startDrag = args; | |
startZoom = zoom; | |
startOffset = offset; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment