在 Beamer 中制作线条动画

在 Beamer 中制作线条动画

下面的代码需要改成动画,代码中foreach的地方,每个数字对应一帧,一共20帧,这样动画运行时,线就实时画出来了。

\documentclass{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}

\path[use as bounding box] (0,0) rectangle (11.5,12);

\gdef\oldy{-2}  
\foreach \x in {-2.9,-2.85,-2.8,...,-1.9}
    {
        \pgfmathsetmacro{\y}{0.2*rand-1.6}
        \pgfmathsetmacro{\oldx}{\x-0.05}
        \draw (\oldx+8.5,\oldy+11) -- (\x+8.5,\y+11);
        \xdef\oldy{\y}
    }

\end{tikzpicture}
\end{document}

在此处输入图片描述

到目前为止的代码。但是,每次迭代时行都会发生变化。

\documentclass{beamer}
\usepackage{tikz,animate}
\newcounter{upperbound}

\begin{document}

    \begin{frame}
        \frametitle{ABC}
        \begin{animateinline}[%
            controls,
            begin={\begin{tikzpicture}
                \foreach [count=\i] \j in {a,...,u}
                \node [scale=0.02] (\j) at (\i*0.30,0+rand*0.2) {};},
            end={\end{tikzpicture}}
            ]{5}
            \multiframe{20}{iCount=2+1}{%
                \setcounter{upperbound}{\iCount}
                \foreach [remember=\j as \k (initially a)] \j in {b,...,\alph{upperbound}} {
                    \draw (\k) -- (\j);
                }
            }
        \end{animateinline}
    \end{frame}
\end{document}

答案1

动画图的帧是通过反复将新线段附加到先前保存的图状态来构建的。保存图的状态可确保每个线段仅计算一次随机数。该解决方案利用了以下包xsavebox

\documentclass{standalone}

\usepackage{tikz}
\usepackage{animate}
\usepackage{xsavebox}

\begin{document}

\gdef\oldy{-2}
%empty first frame:
\xsbox{mygraph}{\tikz \path[use as bounding box] (5.5,8.95) rectangle (6.6,9.65);}%

\begin{animateinline}[controls,scale=5]{8}
  \xusebox{mygraph}
\newframe
  \multiframe{20}{rx=-2.9+0.05}{%
    \pgfmathsetmacro{\y}{0.2*rand-1.6}%
    \xsbox{mygraph}{%
      %repeat previous graph
      \makebox[0pt][l]{\xusebox{mygraph}}%
      %append new line segment
      \begin{tikzpicture}
      \path[use as bounding box] (5.5,8.95) rectangle (6.6,9.65);
      \pgfmathsetmacro{\oldx}{\rx-0.05}
      \draw [line cap=round] (\oldx+8.5,\oldy+11) -- (\rx+8.5,\y+11);
      \end{tikzpicture}%
    }%
    \xusebox{mygraph}%
    \xdef\oldy{\y}%
  }
\end{animateinline}

\end{document}

相关内容