Geomerative: Changing fills + saveShape

Hello!

I am importing an SVG using the Geomerative library and would like to change the fill colors of the paths. I would then like to save the changes as an SVG file.

In this example, based on “Tutorial_16_HelloSVGtoPDF”, the colors of the fills are randomly changed and displaying properly. However, the saved file is identical to the original SVG. Suggestions?

Thanks!
Drew

import geomerative.*;

RShape grp;
String fn;


void setup() {
  size(400, 400);
  smooth();

  RG.init(this);
  fn = "bot1";
  grp = RG.loadShape(fn+".svg");

  noLoop();
}

void draw() {
  background(255);
  grp.draw();

  for (int i=0; i<grp.countChildren(); i++) {
    RG.ignoreStyles(true);    
    fill(color(random(255)));
    noStroke();
    grp.children[i].draw();
  }
}

void keyPressed() {
  if (key == 's') {
    RG.saveShape(fn+"_newColors.svg", grp);
    println("saved");
    exit();
  }
}

Using a function from this post:

we can get all the children even if they are nested deep.

import geomerative.*;

RShape grp;
RShape[] children;
String fn;

void setup() {
  size(400, 400);

  RG.init(this);
  //RG.ignoreStyles(true);   

  fn = "bot1";
  grp = RG.loadShape(fn+".svg");
  children = getAllChildren(grp);

  noLoop();
  noStroke();
}

void draw() {
  background(255);

  for (int i = 0; i < children.length; i++) {
    color c = color(random(255), random(255), random(255));
    children[i].setFill(c);
    children[i].draw();
  }
}

void mousePressed() {
  redraw();
}

void keyPressed() {
  if (key == 's') {
    RG.saveShape(fn+"_newColors.svg", grp);
    println("saved");
    exit();
  }
}

// https://discourse.processing.org/t/finding-all-rshape-children-recursively-geomerative/10241/2
RShape[] getAllChildren(RShape shp) {
  ArrayList<RShape> result = new ArrayList<RShape>();
  int numChildren = shp.countChildren();
  if (numChildren != 0) {
    for (int i = 0; i < numChildren; i++) {
      RShape[] children = getAllChildren(shp.children[i]);
      for (int j = 0; j < children.length; j++) {
        result.add(children[j]);
      }
    }
  } else {
    result.add(shp);
  }
  return result.toArray(new RShape[result.size()]);
}
2 Likes

Thank you, that works like a charm!