如何在页面上移动自定义的 Tikz 命令

如何在页面上移动自定义的 Tikz 命令

我有一个自定义命令,它可以为我创建一张漂亮的图片(该自定义命令取代了 5 个绘图命令),我希望能够在我的文档中复制和移动这张图片。这样我就可以节省时间并为我的文档获得相同/对称的绘图。我遇到的问题是,现在我已经构建了自定义命令,但我无法在页面上移动它。我构建的最新怪物如下:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes}
\usetikzlibrary{plotmarks}
\let\svtikzpicture\tikzpicture
\def\tikzpicture{\noindent\svtikzpicture}

\newcommand{\branchUp}[2][]{
    \tikz{
           \node[fill=black,regular polygon, regular polygon sides=3,inner sep=1] at (#1 + 0.25,#2+3) {}; \\
    \draw(#1 + 0.25,#2 + 0) -- (#1 + 0.25,#2 + 3);     \\
    \draw(#1 + 0.25,#2 + 1.1) circle(0.2);   \\
    \draw(#1 + 0.25,#2 + 0.9) circle(0.2);   \\
    \draw [thick] (#1 +0,#2 + 2) -- (#1 + 0.5,#2 + 2); \\
    }}

\begin{document}
\begin{tikzpicture}[scale=0.5];

\branchUp (1,1);

\end{tikzpicture}

\end{document}

我真正想要做的是写类似这样的内容:

\branchUp at (1,1)

并让它以 (1,1) 为坐标正确填充我的图形。现在我手动执行此操作,当我必须更改某些内容并进行 12 次以上编辑才能看到细微调整的效果时,这并不好玩。

感谢您的帮助,我还没有找到关于 \newcommand 实现的、不会让我困惑的文档。

答案1

s就是为此而pic设计的。使用 pic,你可以存储一组绘图命令,以便一起使用并经常重复使用它们。它还可以处理自身定位,因此你无需自己定位。

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes}
\usetikzlibrary{plotmarks}
\let\svtikzpicture\tikzpicture
\def\tikzpicture{\noindent\svtikzpicture}

\tikzset{
  branchUp/.pic={
     \node[fill=black,regular polygon, regular polygon sides=3,inner sep=1] at ( 0.25,3) {}; 
    \draw(0.25,0) -- ( 0.25, 3);  
    \draw( 0.25,1.1) circle(0.2);  
    \draw( 0.25,0.9) circle(0.2);  
    \draw [thick] (0,2) -- ( 0.5, 2);
}
}


\begin{document}
\begin{tikzpicture}[scale=0.5];

\fill[red] (1,1) circle[radius=3pt];
\pic at (1,1) {branchUp};


\fill[green] (3,-1) circle[radius=3pt];
\pic at (3,-1) {branchUp};

\end{tikzpicture}

\end{document}

生产

问题示例转换为图片

TikZ/PGF 手册很长,但是现在您了解了图片,您应该能够在其中找到大量使用它们的示例。

(我没有在你的代码中改变这一点,但箭头尖端可以使用库中的箭头来实现arrows.meta

答案2

经过abcdefg的回复,我了解到:

\begin{document}

\begin{tikzpicture}[scale=0.5];

\newcommand{\branchUp}[2]{
           \node[fill=black,regular polygon, regular polygon sides=3,inner sep=1] at (#1 + 0.25,#2+3) {}; \\
    \draw(#1 + 0.25,#2 + 0) -- (#1 + 0.25,#2 + 3);     \\
    \draw(#1 + 0.25,#2 + 1.1) circle(0.2);   \\
    \draw(#1 + 0.25,#2 + 0.9) circle(0.2);   \\
    \draw [thick] (#1 +0,#2 + 2) -- (#1 + 0.5,#2 + 2); \\
    }

\branchUp {0}{6};

\end{tikzpicture}

\end{document}

完全按照我的要求做了,解决了 abcdefg 提出的嵌套问题!

我的命令声明中的 '[2][]' 导致我的 x 值始终为 0。

相关内容