4

Say I've got an .svg file in assets that contains somewhere

<polygon id="collide" fill="none" points="45,14 0,79 3,87 18,92 87,90 98,84 96,66 59,14"/>

What do you think would be the best way to find this polygon and parse its points into a Points[] array?

Thanks!

Roger Travis
  • 8,402
  • 18
  • 67
  • 94
  • 1
    I think the best way it's regex.... – Buda Gavril May 07 '12 at 07:59
  • 3
    XML parser or XPath to get the node and get the `@points` attribute `//polygon[@id='collide']/@points`, split its value by spaces, iterate over it to create `Points`. – Alex May 07 '12 at 08:01
  • 1
    Check question `How to parse XML in Android` http://stackoverflow.com/questions/10089291/how-to-parse-xml-in-android – jcubic May 07 '12 at 08:05
  • 1
    check out this link [1]: http://stackoverflow.com/questions/2969037/svg-to-android-shape – Jackson Chengalai May 07 '12 at 08:11
  • 1
    Will batik (http://xmlgraphics.apache.org/batik/) run on Android? If so you could use it to load the data and then get the data using the SVG DOM. – Robert Longson May 07 '12 at 08:15
  • There is currently no working SVG implementation on Android. Parsing the file into a dom tree and drawing the polygons by yourself should be fine. – Stephan May 07 '12 at 08:47

1 Answers1

7

Like stated in the comment above, using XML and XPath, it can be done easily (no exception checking):

public static Point[] getPoints(String xml) throws Exception {
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = db.parse(new InputSource(new StringReader(xml)));
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = xpath.compile("//polygon[@id='collide']/@points");
    String[] pointsAttr = ((String) expr.evaluate(doc, XPathConstants.STRING)).split("\\p{Space}");
    Point[] points = new Point[pointsAttr.length];
    for (int i = 0; i < pointsAttr.length; ++i) {
        String[] coordinates = pointsAttr[i].split(",");
        points[i] = new Point(Integer.valueOf(coordinates[0]), Integer.valueOf(coordinates[1]));
    }
    return points;
}

I don't know what you have at your disposal on Android.

Alex
  • 25,147
  • 6
  • 59
  • 55
  • Thanks! Only it gives me "java.net.MalformedURLException: Protocol not found: – Roger Travis May 07 '12 at 09:48
  • I edited the code above, the previous code did read the XML from a file, now it reads it from a String, so all you have to do is put the content of your XML into the `xml` variable, and pass it to the function. – Alex May 07 '12 at 11:05