PGraphics and main window, nice code possible?

Hello Processing friends. I wonder if anyone could help please. I have a sketch that renders stuff in a small main window, and when ready renders it at hi-res to a PGraphics which is then saved to a file. My code is ugly, like this:

PGraphics hires; 
if (hiresMode) { hires.ellipse(...) else { ellipse (...); }

and so on, all draw and style commands needing this test. Yuck. I would much prefer something like the following, but I can’t see how to do it:

PGraphics hires, target;
if (hiresMode) { target = highres; } else {target= USUALWINDOW; }
target.ellipse(...); // all commands now are target.command()

so no more if statement madness. Is this possible? And a supplementary question – can target also be used as target.beginDraw() or do we always need to treat a PGraphics specially?

thanks!

Toby

1 Like

You can’t get rid of all the if statements, you might try this

PGraphics hires;
boolean hiresMode = false;
PGraphics pg;
int w, h;

public void setup() {
  size(480, 320, P2D);
  // could also use P2D or P3D since main sketch uses P2D/P3D
  hires = createGraphics(width * 2, height * 2, JAVA2D); 
  pg = getGraphics();
  w = width;
  h = height;
}

public void draw() {
  if (hiresMode) {
    pg.beginDraw();
  }
  pg.background(96);
  pg.stroke(0, 255, 0);
  pg.strokeWeight(2);
  pg.noFill();
  for (int i = 0; i < 100; i++) {
    pg.ellipse(random(w), random(h), random(w/4), random(h/4));
  }
  if (hiresMode) {
    pg.endDraw();
    pg.save("img-" + frameCount + ".png");
    swapMode(); // prevent saving multiple frames
  }
}

public void swapMode() {
  hiresMode = !hiresMode;
  pg = (hiresMode) ? hires : getGraphics();
  w = pg.width;
  h = pg.height;
}

public void keyTyped() {
  if (key == 'm') {
    swapMode();
  }
}
2 Likes
PGraphics target, hires;
boolean isHires;

target = isHires? hires : getGraphics();

Processing.GitHub.io/processing-javadocs/core/processing/core/PApplet.html#getGraphics--

1 Like

Thanks a million quark! This works great. Really appreciate your prompt reply.

1 Like

Thanks a lot GoToLoop, very helpful and working fine, and thanks for the link. Cheers! This really is a great Forum!

1 Like