GIF格式动画以其小巧受到大家的广泛欢迎,本文以案例形式做一个总结。
制作GIF动画要用到getframe、frame2im、rgb2ind和imwrite函数,getframe函数用来抓取当前图形窗口中的图像,frame2im函数和rgb2ind函数用来将抓取的图像转为索引图像,imwrite函数用来将索引图像写入GIF格式动画,需要注意的是imwrite函数不能将真彩图像写入GIF格式动画。关于这些函数的具体用法,这里不再详述,请读者自行查阅帮助。下面只给出案例。
【例1】绕螺旋线运动的小球。
% by xiezhh
filename = "运动的小球.gif";
z = linspace(0, 10*pi, 100); %产生一个行向量
x =[20*sin(z),zeros(1,10)];
y =[20*cos(z),20*ones(1,10)];
z =[z,linspace(10*pi,0,10)];
plot3(x, y, z, "r","linewidth", 2); %绘制螺旋线
hold on %图形保持
h = plot3(0,20,0, "." ,"MarkerSize" ,40);
xlabel("X"); ylabel("Y");zlabel("Z"); %添加坐标轴标签
axis([-25,25,-25,25,0,40]); %设置坐标轴范围
view(-210,30); %设置视角
for i = 1:length(x)
set(h, "x>
drawnow; % 刷新屏幕
pause(0.05)
f = getframe(gcf);
imind = frame2im(f);
[imind,cm] = rgb2ind(imind,256);
if i == 1
imwrite(imind,cm,filename,"gif","Loopcount",inf,"DelayTime",0.1);
else
imwrite(imind,cm,filename,"gif","WriteMode","append","DelayTime",0.1);
end
end
动态效果图如下:
【例2】空间曲线
沿空间曲线
运动生成空间曲面的动画。
filename = "空间曲线运动动画.gif";
% 定义空间曲线三维坐标
t0 = linspace(0,pi,30)";
x0 = -0.5*sin(3*t0);
y0 = 2*ones(size(t0));
z0 = t0;
% 绘图
figure
% 绘制空间曲线
h =plot3(x0,y0,z0,"-k","LineWidth",1.5);
hold on
% 绘制三维箭头(代替坐标轴)
quiver3(3.5,2,0,-1,0,0,4,"k","filled","LineWidth",2);
quiver3(3.5,2,0,0,-1,0,3,"k","filled","LineWidth",2);
quiver3(3.5,2,0,0,0,1,5,"k","filled","LineWidth",2);
% 添加注释文字
text(-0.8,2,0.3,"X")
text(3.7,-1.2,0.3,"Y")
text(3.7,1.5,5,"Z")
view(-15,34) % 设置视点位置
axis([-1 6.3 -2 3 05]) % 设置坐标轴范围
axis off
title("空间曲线沿空间曲线运动生成空间曲面的演示动画","fontsize",14,"fontweight","bold")
t = linspace(1,10,50);
% 绘制运动轨迹曲线
plot3(2*t.^(3/5)-2,2*sin(t)+2-2*sin(1),log(t),"-.r","LineWidth",2)
n = numel(t);
% 绘制运动过程中扫过的曲面
for i = 1:n-1
% 计算三维曲线的新坐标
ti = linspace(t(i),t(i+1),30);
xx = 2*t(i+1)^(3/5)-2+x0-x0(1);
yy = 2*sin(t(i+1))+2-2*sin(1)+y0-y0(1);
zz = log(t(i+1))+z0-z0(1);
% 更新三维曲线坐标
set(h, "x>
% 计算扫过的曲面的网格点坐标
[th,tv] = meshgrid(ti,t0);
X0 = -0.5*sin(3*tv);
Y0 = 2*ones(size(tv));
Z0 = tv;
Xi = 2*th.^(3/5)-2+X0-x0(1);
Yi = 2*sin(th)+2-2*sin(1)+Y0-y0(1);
Zi = log(th)+Z0-z0(1);
% 绘制运动过程中扫过的曲面
surf(Xi,Yi,Zi)
shading interp
alpha(0.5);% 设置透明度
drawnow; % 刷新屏幕
pause(0.5)
f = getframe(gcf);
imind = frame2im(f);
[imind,cm] = rgb2ind(imind,256);
if i == 1
imwrite(imind,cm,filename,"gif","Loopcount",inf,"DelayTime",0.3);
else
imwrite(imind,cm,filename,"gif","WriteMode","append","DelayTime",0.3);
end
end
动态效果图如下: