rororo
rororo

Reputation: 845

Pycairo: convert path to svg path syntax

I make the following path for the letter T in cairo:

ctx = cairo.Context(surface)
ctx.text_path("T")
ctx.close_path()
c = ctx.copy_path()

print(c) gives me:

move_to 5.980469 -7.171875
line_to 5.980469 -6.320312
line_to 3.562500 -6.320312
line_to 3.562500 0.000000
line_to 2.578125 0.000000
line_to 2.578125 -6.320312
line_to 0.160156 -6.320312
line_to 0.160156 -7.171875
close path
move_to 6.109375 0.000000
close path
move_to 6.109375 0.000000

and I would like to get it in SVG path syntax in the form:

M216.88,153.42l-44.63.12,0-16.1,108.61-.29,0,16.1-44.83.12L236.37,284l-19.14.05Z

... so that I can import it using svgpath2mpl.parse_path.

Upvotes: 1

Views: 273

Answers (1)

Uli Schlachter
Uli Schlachter

Reputation: 9867

Seems like you need to build that SVG path syntax form yourself.

Apparently, one can iterate over a path and get its elements: https://github.com/pygobject/pycairo/blob/d4639c0337073e0e725fb76509bf2c80eaadfa5f/tests/test_path.py#L60-L73

That first number must come from here and indicates the kind of operation: https://pycairo.readthedocs.io/en/latest/reference/enums.html#cairo.PathDataType

So.... something like this, I guess:

result = ""
for kind, points in ctx.copy_path():
    points = list(points)
    points = ",".join(str(i) for i in points)
    if kind == cairo.PathDataType.MOVE_TO:
        result += "M" + points
    elif kind == cairo.PathDataType.LINE_TO:
        result += "L" + points
    elif kind == cairo.PathDataType.CURVE_TO:
        result += "C" + points
    elif kind == cairo.PathDataType.CLOSE_PATH:
        result += "Z"
    else:
        assert(False, "Path is broken")

No idea whether the above actually works nor whether it produces a correct svg path (do I need upper-case or lower-case letters?). This should just illustrate the idea.

Upvotes: 1

Related Questions