Inkscape SVG编辑器内置了一些简洁的路径操作工具.我特别感兴趣的是以编程方式访问的是偏移函数,它(尝试)创建一条与现有路径固定距离的路径,如此处所示(黑线)偏离红线):
我希望能够从Python程序执行此操作.
Inkscape具有基本的脚本支持,但它基本上只包括调用非交互式菜单命令 – 例如,您可以创建一个从现有路径插入或开始的路径,但仅限于1px或10px,而不是用户指定的路径量.所以这在这里似乎没用.
是否有一个库或其他工具,我可以在Python中进行这些类型的路径转换(理想情况下是SVG文件)?
解决方法:
这有问题.您可以创建偏移路径的视觉近似(或近似路径),但贝塞尔曲线或椭圆弧的偏移曲线通常不是贝塞尔曲线或椭圆弧.
也就是说,有明确的说明如何在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')
标签:python,svg,vector-graphics