动画技术
您可以使用四种基本方法在 MATLAB® 中创建动画。
编程方式 | 描述 | 示例 |
---|---|---|
使用循环方式更新数据。 | 更新图形对象的属性并使用循环方式在屏幕上显示更新。这一方法对于在图大部分保持不变的情况下创建动画非常有用。例如,使用循环方式设置 | |
应用矩阵变换。 | 将变换应用于对象。当您想要同时更改一组对象的位置和方向时,此方法非常有用。将一些图形对象归组为某一变换对象的子级。使用 | |
创建一个动画 GIF 文件。 | 以循环方式使用 | |
创建一个影片。 | 以循环方式使用 |
通过使用循环方式更新数据来创建动画
创建一个沿直线移动的标记的动画。
x = linspace(0,10,500); y = sin(x); % Plot a line and a marker plot(x,y) hold on mkr = scatter(NaN,NaN,[],"red","filled"); hold off xlim([0 10]) ylim([-1 1]) zlim([-1 1]) % Move the marker along the line for i = 1:length(x) mkr.XData = x(i); mkr.YData = y(i); drawnow end
使用矩阵变换创建动画
以动画方式显示绘图的一种高效方法是向一个或多个对象应用变换矩阵,而不是对所有点进行迭代。您可以使用的变换包括平移、旋转和缩放。您还可以定义您自己的变换矩阵。
创建一个绕任意轴旋转 2π 弧度的球体的动画。
使用
sphere
函数创建球体的坐标。创建一个名为
grp
的Transform
对象。然后通过调用surf
函数并将父对象指定为grp
,将球体绘制为Surface
对象。显示坐标区网格线并在三维视图中显示图框。
创建一个
for
循环,它逐步遍历从 0 到 2π 的 300 个等间距角度值,在每次迭代中将球体旋转一个小角度。使用makehgtform
函数为每个小旋转角度创建变换矩阵。然后设置grp
的Matrix
属性以执行旋转。在每次循环迭代结束时调用
drawnow
命令以更新图窗显示。
% Create the coordinates of a sphere figure ax = axes; [x,y,z] = sphere(270); % Create transform object and plot the sphere grp = hgtransform(Parent=ax); s = surf(ax,x,y,z,z,Parent=grp,EdgeColor="none"); % Display grid lines and show the plot box in 3-D grid on view(3) axis vis3d axis tight manual % Rotate the sphere by small angles in a loop for ang = linspace(0,2*pi,300) tm = makehgtform("axisrotate",[1,1,1],ang); grp.Matrix = tm; drawnow end
创建动画 GIF 文件
创建一个沿抛物线移动的标记的动画 GIF 文件。
绘制一条带一个标记的抛物线。
创建一个
for
循环,它在每次迭代中更改标记的位置。在每次循环迭代结束时,使用
exportgraphics
函数将图窗捕获为动画 GIF 文件的帧。当您指定Append=true
名称-值参量时,exportgraphics
捕获当前帧并将其追加到指定的 GIF 文件。生成的
parabola.gif
文件保存到当前文件夹。
% Plot a parabola and a marker x = -10:0.5:10; y = x.^2; p = plot(x,y,"-o",MarkerFaceColor="red"); % Move the marker along the parabola and capture frames in a loop for i=1:41 p.MarkerIndices = i; exportgraphics(gca,"parabola.gif",Append=true) end
创建并播放影片
通过以循环方式使用 getframe
函数创建一个形状不断变化的曲面图的影片。getframe
函数将影片帧捕获到一个结构体数组中,您可以使用 movie
函数播放影片。
使用
surf
函数将peaks
函数的坐标绘制为曲面,并将Surface
对象保存为变量s
。使用
axis tight manual
命令将图框紧密定位在曲面周围并冻结坐标区范围。创建一个名为
F
的由 40 个结构体组成的数组以包含动画帧。创建一个
for
循环,它在每次迭代中更改曲面的形状。在每次循环迭代结束时,使用
drawnow
命令更新图窗,并使用getframe
函数捕获影片帧。生成的影片保存为结构体数组
F
。
% Plot a surface Z = peaks; s = surf(Z); axis tight manual % Change the shape of the surface and capture frames loops = 40; F(loops) = struct('cdata',[],'colormap',[]); for j = 1:loops Zframe = sin(j*pi/10)*Z; s.ZData = Zframe; drawnow F(j) = getframe(gcf); end
播放影片两次。
fig = figure; movie(fig,F,2)
另请参阅
函数
hgtransform
|makehgtform
|exportgraphics
|getframe
|movie
|writeVideo