SVG路径操作

4
Inkscape SVG编辑器内置了一些不错的路径操作工具。我特别感兴趣的是可编程访问的偏移函数,该函数试图创建一个距离现有路径固定距离的路径,如下所示(黑色线条是红色线条的偏移): path offset 我想从Python程序中执行此操作。
Inkscape具有基本的脚本支持,但它基本上只包含调用非交互式菜单命令——例如,您可以创建一个从现有路径中嵌入或扩展的路径,但仅以精确的1px或10px为单位,而不能按用户指定的量。因此,在这里似乎没有用处。
是否有库或其他工具可以在Python中执行这些类型的路径转换(理想情况下是SVG文件)?

有一个很好的工具 - Snap.svg,它是用于SVG的JavaScript库。我认为你不会找到Python的库,因为SVG是浏览器技术,所有开发人员都试图为前端编写库,而不是后端。 - Slawa Eremin
我已经查看了Snap.svg文档,它看起来是一个有用的库,但相当基础。我没有看到任何关于偏移量或任何路径操作的内容。 - Josh
乔希,你找到解决方案了吗? - kryptobs2000
Inkscape是开源的,你可以尝试在它的源代码中搜索。 - cuixiping
1个回答

8
这存在一个问题。你可以创建一条视觉近似(或路径近似)于偏移轨迹,但是贝塞尔曲线或椭圆弧的偏移曲线通常不会是贝塞尔曲线或椭圆弧。
话虽如此,在svgpathtools Python模块的自述文件中有关于如何创建这种偏移曲线的分段线性近似的明确指示(只需点击链接并向下滚动 - 最后一个例子,“高级应用:路径偏移”)。
以下是代码:
from svgpathtools import parse_path, Line, Path, wsvg
def offset_curve(path, offset_distance, steps=1000):
    """Takes in a Path object, `path`, and a distance,
    `offset_distance`, and outputs an piecewise-linear approximation 
    of the 'parallel' offset curve."""
    nls = []
    for seg in path:
        ct = 1
        for k in range(steps):
            t = k / steps
            offset_vector = offset_distance * seg.normal(t)
            nl = Line(seg.point(t), seg.point(t) + offset_vector)
            nls.append(nl)
    connect_the_dots = [Line(nls[k].end, nls[k+1].end) for k in range(len(nls)-1)]
    if path.isclosed():
        connect_the_dots.append(Line(nls[-1].end, nls[0].end))
    offset_path = Path(*connect_the_dots)
    return offset_path



# Examples:
path1 = parse_path("m 288,600 c -52,-28 -42,-61 0,-97 ")
path2 = parse_path("M 151,395 C 407,485 726.17662,160 634,339").translated(300)
path3 = parse_path("m 117,695 c 237,-7 -103,-146 457,0").translated(500+400j)
paths = [path1, path2, path3]

offset_distances = [10*k for k in range(1,51)]
offset_paths = []
for path in paths:
    for distances in offset_distances:
        offset_paths.append(offset_curve(path, distances))

# Note: This will take a few moments
wsvg(paths + offset_paths, 'g'*len(paths) + 'r'*len(offset_paths), filename='offsetcurves.svg')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接