Skip to content

Instantly share code, notes, and snippets.

@micycle1
Created January 4, 2021 19:00
Show Gist options
  • Save micycle1/816b7605dae80705887f5763080f56bc to your computer and use it in GitHub Desktop.
Save micycle1/816b7605dae80705887f5763080f56bc to your computer and use it in GitHub Desktop.
Code to clone PGraphics via reflection
static PGraphics cloneGraphics(PGraphics source) {
final String renderer;
switch (source.parent.sketchRenderer()) {
case "processing.opengl.PGraphics2D":
renderer = P2D;
break;
case "processing.opengl.PGraphics3D":
renderer = P3D;
break;
default: // secondary sketches cannot use FX2D
renderer = JAVA2D;
}
PGraphics clone = source.parent.createGraphics(source.width, source.height, renderer);
clone.beginDraw();
clone.style(source.getStyle());
// A more simple approach would be clone.setStyle(source.style()) it's less
// thorough than reflecting fields
final Field[] fields = source.getClass().getFields();
for (Field field : fields) {
// non-static field and primitive fields
if (!java.lang.reflect.Modifier.isStatic(field.getModifiers()) && (field.getType() == int.class
|| field.getType() == boolean.class || field.getType() == float.class)) {
field.setAccessible(true);
String name = field.getName();
Object value;
try {
value = field.get(source); // get field value from source
// if (name == "fillColor") {
field.set(clone, value); // set clone field value using source
// }
// System.out.println(name + ": " + value.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
source.loadPixels(); // graphics buffer -> int[] buffer
clone.pixels = source.pixels.clone(); // in's int[] buffer -> clone's int[] buffer
clone.updatePixels(); // int[] buffer -> graphics buffer
clone.endDraw();
return clone;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment