tikzset 样式 - 使用命令生成多个 key-val

tikzset 样式 - 使用命令生成多个 key-val

使用 创建带有参数的样式时\tikzset,我可以轻松创建带有参数的“别名”,只要这些参数出现在 key=value 的值部分,例如xshift=#1。我想要做的是获取一个参数,使用命令来处理它,并让该命令生成键值。然而,这并不像我预期的那样工作。

\documentclass[tikz,border=3mm]{standalone}

\usetikzlibrary{positioning}

\NewDocumentCommand{\processxyshift}{m}{%
% in my use, I'm goinng to do something more fancy, hence why I want to use a command
xshift=#1cm,yshift=#1cm
}

\tikzset{
xs/.style={xshift=#1}  % #1 appearing in the value works as long as it's preceded by a key
xys/.style={\processxyshift{#1}} % but if I want some command to print a key=value output, it fails
}

\begin{document}
\begin{tikzpicture}
\node(start) at (0,0) {Hello World};
\node[anchor=west](end)   at ([xs=1]start.east) {Over here!};  % works
\node[anchor=west](end)   at ([xys=2]start.east) {Over here!}; % this does not work
\end{tikzpicture}
\end{document}

答案1

你想要.estyle,但是\newcommand,没有\NewDocumentCommand。或者\NewExpandableDocumentCommand

\documentclass[border=3mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}

\newcommand{\processxyshift}[1]{%
  % in my use, I'm going to do something more fancy
  xshift=#1cm,yshift=#1cm
}

\tikzset{
  xs/.style={xshift=#1},
  xys/.estyle={\processxyshift{#1}},
}

\begin{document}

\begin{tikzpicture}
\node(start) at (0,0) {Hello World};
\node[anchor=west](end) at ([xs=1]start.east) {Over here!};
\node[anchor=west](end) at ([xys=2]start.east) {Over here!};
\end{tikzpicture}

\end{document}

在此处输入图片描述

答案2

除了.estyle(完全扩展输入)之外,您还可以使用.expand once处理程序仅扩展输入一次。在示例中,这没有什么区别,但如果您的宏扩展到不应进一步扩展的内容,则应使用.expand once

\documentclass[border=3mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}

\newcommand{\processxyshift}[1]{%
  % in my use, I'm going to do something more fancy
  xshift=#1cm,yshift=#1cm
}

\tikzset{
  xs/.style={xshift=#1},
  xys/.style/.expand once={\processxyshift{#1}},
}

\begin{document}

\begin{tikzpicture}
\node(start) at (0,0) {Hello World};
\node[anchor=west](end) at ([xs=1]start.east) {Over here!};
\node[anchor=west](end) at ([xys=2]start.east) {Over here!};
\end{tikzpicture}

\end{document}

答案3

您可以使用.code处理程序和\pgfkeysalso

\documentclass[tikz,border=3mm]{standalone}

\usetikzlibrary{positioning}

\newcommand{\processxyshift}[1]{%
  % in my use, I'm goinng to do something more fancy, hence why I want to use a command
  \pgfkeysalso{xshift=#1cm,yshift=#1cm}
}

\tikzset{
  xs/.style={xshift=#1},
  xys/.code={\processxyshift{#1}},
  xys2/.code={
    % in my use, I'm goinng to do something more fancy, hence why I want to use a command
    \typeout{#1}
    \pgfkeysalso{xshift=#1cm,yshift=#1cm}
  }
}

\begin{document}
\begin{tikzpicture}
\node(start) at (0,0) {Hello World};
\node[anchor=west](end)   at ([xs=1]start.east) {Over here 1!};  % works
\node[anchor=west](end)   at ([xys=2]start.east) {Over here 2!}; % this does not work
\node[anchor=west](end)   at ([xys2=3]start.east) {Over here 3!}; % this does not work
\end{tikzpicture}
\end{document}

相关内容