MATLAB中的动画 - 同时动画几个移动点

时间:2017-01-11 16:37:21

标签: matlab animation matlab-figure

下面是绘制2D Bezier曲线的MATLAB函数。我的目标是为背景中使用的所有不同组件设置动画,即贝塞尔曲线的切线,控制点之间的点等。我希望在此结束时看到类似于动画的内容。视频:Cubic Bezier Curves - Under the Hood

我的问题是,当我试图同时绘制控制点之间运行的所有点时,我会发出相当严重的闪烁。

我对使用MATLAB的动画很新,并且从各种来源中提取了大量动画代码。任何帮助都会很棒!

P.S。我一直使用的控制点是[1 1;2 6;7 7;10 2]

function bezier_anim(coords) % Coords to be entered in the format [x1 y1;x2 y2;...;xn yn]

close all

n = length(coords(:,1)); % Number of control points

syms t;
syms p;
B = zeros(2,1); % Bezier function

for i = 0:n-1
    % Equation for Bezier curve
    B = B + nchoosek(n-1,i) .* (1-t).^(n-1-i) .* t^i .* coords(i+1,:).'; 
end

for i = 1:n
   % Plot and label P_i
   x=coords(i,1);
   y=coords(i,2);
   plot(x,y,'kx')
   txt1 = '$$\mathbf{P}_';
   txt2 = num2str(i-1);
   txt3 = '$$';
   txt = [txt1 txt2 txt3];
   text(x,y,txt,'Interpreter','latex','VerticalAlignment','bottom','HorizontalAlignment','center')
   hold on
end

plot(coords(:,1),coords(:,2),'k--') % Plot lines between control points

L = sym('t',[2 n-1]); % Vector where eqs of lines are to be added

for i = 1:n-1 
    % Parametric equations of the straight lines between the control
    % points, for p between 0 and 1
    L(1,i) = (1-p)*coords(i,1) + p*coords(i+1,1);
    L(2,i) = (1-p)*coords(i,2) + p*coords(i+1,2);
end

% Animation of Bezier curve
g = animatedline;
x = matlabFunction(B(1));
y = matlabFunction(B(2));

for t = 0:0.01:1
    l = subs(L,'p',t); % Substitute current t value into eq for the lines
    addpoints(g,x(t),y(t));
    for k = 1:length(l(1,:)) % Plot all points running along each line simultaneously
        h(k) = plot(l(1,k),l(2,k),'r.');
        drawnow
        delete(h(k)) % Delete current point after it has been drawn 
                     % so there is not a trail
    end
    drawnow
end

end

1 个答案:

答案 0 :(得分:3)

您可能会因为在最后一个嵌套for循环内创建新的绘图对象而不是更新现有的绘图对象而降低性能。您可以重写该循环以修改现有绘图对象的XDataYData属性

% Animation of Bezier curve

% Create the plot object to use later
hplot = plot(NaN, NaN, 'r.');

for t = 0:0.01:1
    l = subs(L,'p',t); % Substitute current t value into eq for the lines
    addpoints(g,x(t),y(t));

    for k = 1:length(l(1,:)) % Plot all points running along each line simultaneously
        % Update the position of the existing plot object
        set(hplot, 'XData', l(1,k), 'YData', l(2,k))
        drawnow
    end
    drawnow
end

您还可以确保将图形的DoubleBuffer属性设置为'on'以减少闪烁。

set(gcf, 'DoubleBuffer', 'on')

另外,我认为"闪烁"实际上可能只是MATLAB正在快速渲染红点的运动(并且它在线段之间跳跃)并且你将其视为闪烁。我认为而不是那个内循环,同时在所有线段上绘制红点可能更容易看到

% Create the plot object to use later
hplot = plot(NaN, NaN, 'ro');

for t = 0:0.01:1
    l = subs(L,'p',t); % Substitute current t value into eq for the lines
    set(hplot, 'XData', l(1,:), 'YData', l(2,:));

    addpoints(g,x(t),y(t));

    drawnow
end