您的位置:首页 > 编程语言 > MATLAB

利用de Casteljau算法绘制Bezier曲线

2017-02-25 20:39 381 查看
在opengl版的de Casteljau算法http://blog.csdn.net/lafengxiaoyu/article/details/51296411的基础上进行代码的改写,看得出来在MATLAB之下代码还是比较简单的,直接放代码

function decasteljau( vertices )

Dim=size(vertices,1);%二位或者三维空间
NumPoint=size(vertices,2)-1;%点的个数

x=zeros(1,NumPoint+1);y=zeros(1,NumPoint+1);z=zeros(1,NumPoint+1);
xx=[];yy=[];zz=[];
if Dim==2
for t=0:0.001:1;
for i=1:NumPoint
for j=0:NumPoint-i
if i==1
x(j+1) = (1 - t)*vertices(1,j+1) + t*vertices(1,j+2);
y(j+1) = (1 - t)*vertices(2,j+1) + t*vertices(2,j+2);
continue;
end
x(j+1) = x(j+1) * (1 - t) + x(j + 2) * t;
y(j+1) = y(j+1) * (1 - t) + y(j + 2) * t;
end
end
xx(end+1)=x(1);
yy(end+1)=y(1);
end
plot(vertices(1,:),vertices(2,:),'b');
hold on;grid on;
axis tight;
xlabel('X');ylabel('Y');
plot(xx,yy,'r');
end

if Dim==3
for t=0:0.001:1;
for i=1:NumPoint
for j=0:NumPoint-i
if i==1
x(j+1) = (1 - t)*vertices(1,j+1) + t*vertices(1,j+2);
y(j+1) = (1 - t)*vertices(2,j+1) + t*vertices(2,j+2);
z(j+1) = (1 - t)*vertices(3,j+1) + t*vertices(3,j+2);
continue;
end
x(j+1) = x(j+1) * (1 - t) + x(j + 2) * t;
y(j+1) = y(j+1) * (1 - t) + y(j + 2) * t;
z(j+1) = z(j+1) * (1 - t) + z(j + 2) * t;
end
end
xx(end+1)=x(1);
yy(end+1)=y(1);
zz(end+1)=z(1);
end
plot3(vertices(1,:),vertices(2,:),vertices(3,:),'b');
hold on;grid on;
axis tight;
axis([0.5,1.5,0.5,1.5,0,0.7]);
xlabel('X');ylabel('Y');zlabel('Z');
plot3(xx,yy,zz,'r');
view(3);
end

end
下面还是对二维和三维的两种情况进行运行

vertices=[0.8 0.8 0;1.4 0.6 0;1.5 0.7 0.5;1.5 1.5 .5;0.6 1.4 0;1.5 1.5 0]';
decasteljau( vertices )
运行结果如下图



二维的情况

vertices = [0 3; 3 7;7 2; 9 6;13 3]';


运行结果如下图



上一篇博客的结果是一样的,well done
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息