下面是一个使用Python和Matplotlib库绘制贝塞尔曲线,并在曲线上的点处绘制垂直线的示例代码:
import numpy as np
import matplotlib.pyplot as plt
def bezier_curve(points, t):
n = len(points) - 1
result = np.zeros(points[0].shape)
for i in range(n+1):
result += binomial_coefficient(n, i) * (1-t)**(n-i) * t**i * points[i]
return result
def binomial_coefficient(n, k):
return np.math.factorial(n) / (np.math.factorial(k) * np.math.factorial(n-k))
def plot_bezier_curve(points, num_points=100):
t = np.linspace(0, 1, num_points)
curve_points = np.array([bezier_curve(points, ti) for ti in t])
plt.plot(points[:, 0], points[:, 1], '-o', label='Control Points')
plt.plot(curve_points[:, 0], curve_points[:, 1], label='Bezier Curve')
# 绘制垂直线
for i in range(len(points)):
x = curve_points[i, 0]
y = curve_points[i, 1]
dx = -0.1 # 垂直线的长度
dy = 0.1
angle = np.arctan2(dy, dx)
plt.plot([x, x + dx], [y, y + dy], 'r--')
plt.legend()
plt.axis('equal')
plt.show()
# 示例用法
control_points = np.array([[0, 0], [1, 3], [2, -3], [3, 0]])
plot_bezier_curve(control_points)
此代码使用bezier_curve
函数计算贝塞尔曲线上的点,然后使用Matplotlib库绘制控制点和贝塞尔曲线。在绘制垂直线时,通过计算曲线上每个点的斜率,确定垂直线的角度和长度,然后绘制垂直线。