views:

258

answers:

2

I was wondering if there was a tool to convert a path data like "M 0 0 l 10 10" to it's equivalent line/curve segment code.

Currently I'm using:

string pathXaml = "<Path xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" Data=\"M 0 0 l 10 10\"/>";
Path path = (Path)System.Windows.Markup.XamlReader.Load(pathXaml);

It appears to me that calling XamlParser is much slower than explicitly creating the line segments. However converting a lot of paths by hand is very tedious.

+1  A: 

There's nothing built-in to generate C# or VB code from the geometry minilanguage, but you could create one as follows:

  • Emit C# or VB code for new-ing up a PathGeometry.
  • Call PathFigureCollection.Parse on your path string. This will return a PathFigureCollection instance.
  • Iterate over the PathFigureCollection. For each figure:
    • Write out C# or VB code for new-ing a PathFigure object and adding it to the PathGeometry.Figures collection.
    • Iterate over the figure's Segments collection. For each segment, analyse its type and emit type-dependent code for new-ing up the appropriate kind of PathSegment, setting its properties and adding it to the current PathFigure.

Whether this is more or less tedious than converting the paths by hand is something only you can decide, though... it probably depends on how many different kinds of segment you need to handle (i.e. how many different kinds of segment appear in your path strings), since you will have to write separate code for LineSegments, ArcSegments, etc.

EDIT: Thanks to Anvaka in comments for simplifying the original answer by drawing my attention to PathFigureCollection.Parse.

itowlson
Hi itowlson, it looks like author of the question uses XamlReader which is indeed slow for this kind of operation. Instead you could suggest him to use *Geometry.Parse()* method. Which is faster than XamlReader. BTW, in your scenario you could also omit converters, and use *PathFigureCollection.Parse()* :)... I still think your answer is correct.
Anvaka
Anvaka: boy, is my face red. I didn't even realise those methods were public -- I thought the only way to get at them was via the converter. I will update -- many thanks! (Regarding XamlReader vs string parsing, it looks like he edited the question while I was writing -- in the original version he was setting directly setting the Path property from a string in code.)
itowlson
Thanks for all the answers, yeah I did edit the question, the code in my program is sligthly different but the idea is the same. I'll implement the suggested optimization.
A: 

This program will do the conversion: http://stringtopathgeometry.codeplex.com/