python如何画svg路径_python – SVG路径操作

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python turtle库不支持SVG fill_rule属性,但是可以通过一些方法模拟它的效果。 一种简单的方法是使用Python的绘图库,例如Pillow或OpenCV。这些库可以将SVG文件读入并绘制它们。然后,可以使用Python的算法来模拟fill_rule=”evenodd”。 另一种方法是使用Python turtle库中的pencolor函数,并使用“XOR”操作来模拟fill_rule=”evenodd”。当turtle遇到边界时,它将自动填充形状。然而,它没有内部的fill_rule选项来控制填充。 以下是一个使用“XOR”操作来模拟fill_rule=”evenodd”的例子: ``` import turtle def draw_shape(): turtle.penup() turtle.goto(0,0) turtle.pendown() turtle.begin_fill() turtle.fillcolor("red") # Draw shape here turtle.circle(50) turtle.end_fill() # XOR fill the shape turtle.pencolor("white") turtle.fillcolor("white") turtle.begin_fill() turtle.goto(0,0) turtle.pendown() turtle.circle(50) turtle.end_fill() draw_shape() ``` 在这个例子中,我们首先用红色填充一个圆形。然后,我们使用pencolor函数将笔的颜色设置为白色,使用fillcolor函数将填充颜色设置为白色,然后使用begin_fill函数开始一个新的填充。我们移动到圆形的中心,然后出一个相同大小的圆形。这将使得两个圆形的重叠区域被“XOR”操作,形成一个“evenodd”填充的效果。最后,我们使用end_fill函数结束填充。 这个方法可能不是最完美的,但它是一种可以在Python turtle中模拟fill_rule=”evenodd”的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值