如何从 svgpathtools 贝塞尔曲线获取坐标列表?

How do I get a coordinates list from an svgpathtools bezier curve?

我有 python 创建贝塞尔曲线的代码,我从中创建贝塞尔曲线。

这是我的导入:

import from svgpathtools import Path, Line, CubicBezier

这是我的代码:

    bezier_curve = CubicBezier(start_coordinate, control_point_1, control_point_2, end_coordinate)
    bezier_path = Path(bezier_curve)

我想创建构成这条曲线的坐标列表,但是我正在阅读的 documentation 中的 none 提供了一种直接的方法。 bezier_curve和bezier_path只有起点、终点和控制点的参数。

看起来是个很有道理的问题。很惊讶没有答案。我最近不得不自己做这个,秘诀是point()

这是我完成它的方法,使用您的样板作为起点:

from svgpathtools import Path, Line, CubicBezier

bezier_curve = CubicBezier(start=(300+100j), control1=(100+100j), control2=(200+200j), end=(200+300j))
bezier_path = Path(bezier_curve)

NUM_SAMPLES = 10

myPath = []
for i in range(NUM_SAMPLES):
    myPath.append(bezier_path.point(i/(NUM_SAMPLES-1)))

print(myPath)

输出:

[(300+100j), (243.8957475994513+103.56652949245542j), (206.72153635116598+113.71742112482853j), (185.1851851851852+129.62962962962962j), (175.99451303155004+150.480109739369j), (175.85733882030178+175.44581618655695j), (181.4814814814815+203.7037037037037j), (189.57475994513032+234.43072702331963j), (196.84499314128942+266.8038408779149j), (200+300j)]

上面给出的答案对我来说非常有效。我只需要对代码做一个小小的修改:

from svgpathtools import Path, Line, CubicBezier

bezier_curve = CubicBezier(start=(300+100j), control1=(100+100j), control2=(200+200j), end=(200+300j))
bezier_path = Path(bezier_curve)

NUM_SAMPLES = 10

myPath = []
for i in range(NUM_SAMPLES):
    myPath.append(bezier_path.point(i/(**float(NUM_SAMPLES)**-1)))

print(myPath)

更改 i/(NUM_SAMPLES -1) by i/(float(NUM_SAMPLES) -1) 可确保曲线参数化从 0 到 1 时的正确行为。否则只会生成整数除法。

#to demonstrate lines and cubics, improving readibility

from svgpathtools import Path, Line, CubicBezier

cubic = CubicBezier(300+100j, 100+100j, 200+200j, 200+300j)  # A cubic beginning at (300, 100) and ending at (200, 300)
line = Line(200+300j, 250+350j)  # A line beginning at (200, 300) and ending at (250, 350)

number_of_points = 10

cubic_points = []

for i in range(number_of_points):
    cubic_points.append(cubic.point(i/(NUM_SAMPLES-1)))

print('cubic points', path_points)

line_points = []

for i in range(number_of_points):
    line_points.append(line.point(i/(NUM_SAMPLES-1)))

print('line points', path_points)