Cheers,
Rob
- Viewport viewport;
- float zoomFactor = 1;
- boolean dragging = false;
- void setup() {
- size(400, 400);
- smooth();
- textFont(createFont("Courier New", 12), 12);
- viewport = new Viewport(50, 50, 50, 50);
- }
- void draw() {
- background(0);
- if(dragging){
- viewport.pan(mouseX, mouseY);
- }
- g.setMatrix(viewport.mat);
- noFill();
- stroke(150);
- for(int j = 0; j < 10; j++)
- for(int i = 0; i < 10; i++)
- ellipse(50+i*20, 50+j*20, 20, 20);
- g.resetMatrix();
- PVector p = viewport.screenToImageCoords(new PVector(mouseX, mouseY));
- text(p.x + " " + p.y, mouseX, mouseY);
- }
- void mousePressed(){
- if(mouseButton == RIGHT) dragging = true;
- }
- void mouseReleased(){
- dragging = false;
- }
- void keyPressed() {
- if(keyCode == UP || keyCode == DOWN) {
- if(keyCode == UP) zoomFactor *= 1.1;
- if(keyCode == DOWN) zoomFactor *= 0.9;
- viewport.zoomOnPoint(mouseX, mouseY, zoomFactor);
- }
- }
- class Viewport {
- float x, y, w, h, iw, ih;
- PMatrix2D mat, inverseMat;
- Viewport(float x, float y, float w, float h) {
- this.x = x;
- this.y = y;
- this.w = iw = w;
- this.h = ih = h;
- mat = new PMatrix2D();
- inverseMat = new PMatrix2D();
- }
- void pan(float ox, float oy){
- mat.translate(ox, oy);
- }
- void zoomOnPoint(float ox, float oy, float zoomFactor) {
- //PVector pImg = screenToImageCoords(new PVector(ox, oy));
- mat = new PMatrix2D();
- mat.translate(ox, oy);
- mat.scale(zoomFactor);
- mat.translate(-ox, -oy);
- inverseMat = new PMatrix2D(mat);
- inverseMat.invert();
- PVector out = mat.mult(new PVector(0, 0), null);
- x = out.x;
- y = out.y;
- w = iw * zoomFactor;
- h = ih * zoomFactor;
- }
- PVector screenToImageCoords(PVector p){
- return inverseMat.mult(p, null);
- }
- PVector imageToScreenCoords(PVector p){
- return mat.mult(p, null);
- }
- void draw() {
- stroke(255, 0, 0);
- noFill();
- rect(0, 0, iw, ih);
- }
- }
1