Google Tag Manager

2013/02/26

Get SVG from PathIterator

Code

private StringBuilder makeStarburstSvg(PathIterator pi, int sz, String style, String desc) {
  StringBuilder sb = new StringBuilder();
  sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
  //...
  sb.append(String.format("<svg width=\"%d\" height=\"%d\" xmlns=\"%s\">%n", sz, sz, w3));
  sb.append(String.format("  <desc>%s</desc>%n", desc));
  sb.append("  <path d=\"");
  double[] c = new double[6];
  while(!pi.isDone()) {
    switch(pi.currentSegment(c)) {
      case PathIterator.SEG_MOVETO:
        sb.append(String.format("M%.2f,%.2f ", c[0], c[1])); break;
      case PathIterator.SEG_LINETO:
        sb.append(String.format("L%.2f,%.2f ", c[0], c[1])); break;
      case PathIterator.SEG_QUADTO:
        sb.append(String.format("Q%.2f,%.2f,%.2f,%.2f ",c[0],c[1],c[2],c[3]));
        break;
      case PathIterator.SEG_CUBICTO:
        sb.append(String.format("C%.2f,%.2f,%.2f,%.2f,%.2f,%.2f ",c[0],c[1],c[2],c[3],c[4],c[5]));
        break;
      case PathIterator.SEG_CLOSE:
        sb.append("Z"); break;
    }
    pi.next();
  }
  sb.append(String.format("\" style=\"%s\" />%n</svg>%n", style));
  return sb;
}

References

3 comments:

  1. The batik SVGGraphics2D is similar: http://xmlgraphics.apache.org/batik/using/svg-generator.html

    ReplyDelete
  2. Thank you for the information.
    I think the Batik is a good choice(it supports almost all of the SVG specification).
    In this example dealing with just one Shape and will explain how to use a PathIterator, so might need to change this article title :)

    ReplyDelete
  3. This comment has been removed by a blog administrator. our sclinbio.com

    ReplyDelete