SVG路径操作

2024-05-23 19:11:32 发布

您现在位置:Python中文网/ 问答频道 /正文

inkscapesvg编辑器内置了一些简洁的路径操作工具。我对以编程方式访问的一个特别感兴趣的是offset函数,它(试图)创建一个与现有路径保持固定距离的路径,如这里所示(黑线是红线的偏移):

path offset

我希望能够从Python程序执行这个操作。在

从一开始就可以通过调用一个基本的pxe脚本来创建一个基本的路径,或者说不只是一个简单的,用户可以从一开始就创建一个交互式的路径。所以这在这里似乎没用。在

有没有一个库或其他工具可以让我在Python中进行这些路径转换(理想情况下是SVG文件)?在


Tags: 工具函数路径距离编程方式编辑器内置
1条回答
网友
1楼 · 发布于 2024-05-23 19:11:32

这有问题。您可以创建偏移路径的视觉近似(或路径近似),但Bezier曲线或椭圆弧的偏移曲线通常不会是Bezier曲线或椭圆弧。在

也就是说,在svgpathtools python module的自述中,有明确的说明如何创建这种偏移曲线的分段线性近似(只需沿着链接向下滚动-这是最后一个例子,“高级应用程序:偏移路径”)。在

代码如下:

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')

相关问题 更多 >