bezier曲线的de Casteljau算法,并画出曲线生成过程的GIF动图。
(学习过程的一点小收获,浅浅记录一下)
%p^0_i(t)=p^0_i
%p^k_i(t)=(1-t)p^{k-1}_i(t)+t*p^{k-1}_i+1(t)
clear
clc
p=[0 0;3 7;5 2;9 0];%控制顶点
t=linspace(0,1,100);
N=length(t);
n = 3;%3阶
B = zeros(n+1, size(p,1),2);
Bplot = zeros(n+1, size(p,1),2);
Bline=zeros(N,2);
bezier=cell(N,1);
pic_num = 1;
for i=1:N
for j=1:n
for k=1 : n - j + 1
B(1, :,1) = p(:, 1)';
B(1, :,2)=p(:, 2)';
B(j+1, k,1)=(1 - t(i)) * B(j, k,1) + t(i) * B(j, k+1,1);
B(j+1, k,2)=(1 - t(i)) * B(j, k,2) + t(i) * B(j, k+1,2);
end
end
Bline(i,1)=B(4,1,1);
Bline(i,2)=B(4,1,2);
bezier{i}=B;
end
for i=1:N
figure(1);
Bplot=bezier{i,1};
plot(Bplot(1, :,1),Bplot(1, :,2),'r-o',...
Bplot(2,1:n, 1), Bplot(2,1:n, 2), '-go',...
Bplot(3,1:n-1, 1), Bplot(3,1:n-1, 2), '-bo',...
Bplot(4,1:n-2, 1), Bplot(4,1:n-2, 2), '-ko',...
Bline(:,1),Bline(:,2),'k','linewidth', 1.5);
title(sprintf('贝塞尔曲线 (阶数: %d)', 3));
drawnow;
F=getframe(gcf);
I=frame2im(F);
[I,map]=rgb2ind(I,256);
if pic_num == 1
imwrite(I,map,'bezier_line.gif','gif', 'Loopcount',inf,'DelayTime',0.2);
else
imwrite(I,map,'bezier_line.gif','gif','WriteMode','append','DelayTime',0.2);
end
pic_num = pic_num + 1;
end