我想创建一个可以在 tikz 路径中间调用的宏,并且根据其中一个参数表现出不同的行为。
以下是一个示例文档:
\documentclass[a4paper]{amsart}
\usepackage{ifthen, tikz}
\newcommand{\nameandlabel}[2]{%
node [midway, \ifthenelse{\equal{#1}{a}}{above}{below}] {#2}%
}
\begin{document}
\begin{tikzpicture}[xscale = 25mm]
\node (a) at (0, 0) {$A$};
\node (b) at (1, 0) {$B$};
\node (c) at (2, 0) {$C$};
\draw (a) -- (b) node [midway, above] {$f$};
\draw (b) -- (c) \nameandlabel{a}{$g$};
\end{tikzpicture}
\end{document}
本文档无法编译。它导致出现此错误消息,这令人惊讶,因为\equal
这是 ifthen 提供的宏。
! Undefined control sequence.
<argument> \equal
{a}{a}
l.16 \draw (b) -- (c) \nameandlabel{a}{$g$}
;
我在 TeX-LaTeX Stack Exchange 上看到有人讨论说 ifthen 已经过时了,\IfStrEq
可以使用 xstring 包中的宏来代替。所以我将示例更改为以下内容:
\documentclass[a4paper]{amsart}
\usepackage{xstring, tikz}
\newcommand{\nameandlabel}[2]{%
node [midway, \IfStrEq{#1}{a}{above}{below}] {#2}%
}
\begin{document}
\begin{tikzpicture}[xscale = 25mm]
\node (a) at (0, 0) {$A$};
\node (b) at (1, 0) {$B$};
\node (c) at (2, 0) {$C$};
\draw (a) -- (b) node [midway, above] {$f$};
\draw (b) -- (c) \nameandlabel{a}{$g$};
\end{tikzpicture}
\end{document}
但这会导致更难以理解的错误信息:
! Argument of \XC@definec@lor has an extra }.
<inserted text>
\par
l.16 \draw (b) -- (c) \nameandlabel{a}{$g$}
;
为什么这仍然不起作用?
答案1
测试ifthen
都不起作用xstring
扩张它们都做出了内部定义。
如果您使用纯可扩展测试,它就会按您预期的方式工作。
\documentclass[a4paper]{amsart}
\usepackage{ifthen, tikz}
\newcommand{\nameandlabel}[2]{%
node [midway, \ifx a#1above\else below\fi] {#2}%
}
\begin{document}
\begin{tikzpicture}[x = 25mm]
\node (a) at (0, 0) {$A$};
\node (b) at (1, 0) {$B$};
\node (c) at (2, 0) {$C$};
\draw (a) -- (b) node [midway, above] {$f$};
\draw (b) -- (c) \nameandlabel{a}{$g$};
\end{tikzpicture}
\begin{tikzpicture}[x = 25mm]
\node (a) at (0, 0) {$A$};
\node (b) at (1, 0) {$B$};
\node (c) at (2, 0) {$C$};
\draw (a) -- (b) node [midway, above] {$f$};
\draw (b) -- (c) \nameandlabel{b}{$g$};
\end{tikzpicture}
\end{document}
答案2
David Carlisle 的回答直接回答了你的问题。但我认为,在你的情况下,使用条件句更符合 Ti 的精神钾Z 使用.is choice
密钥处理程序。下面是操作方法的示例。
\documentclass[varwidth]{standalone}
\usepackage{tikz}
\tikzset{
ab/.is choice,
ab/a/.style={above},
ab/b/.style={below},
}
\newcommand{\nameandlabel}[2]{%
node [midway,ab=#1] {#2}%
}
\begin{document}
\begin{tikzpicture}[x = 25mm]
\node (a) at (0, 0) {$A$};
\node (b) at (1, 0) {$B$};
\node (c) at (2, 0) {$C$};
\draw (a) -- (b) node [midway, above] {$f$};
\draw (b) -- (c) \nameandlabel{a}{$g$};
\end{tikzpicture}
\begin{tikzpicture}[x = 25mm]
\node (a) at (0, 0) {$A$};
\node (b) at (1, 0) {$B$};
\node (c) at (2, 0) {$C$};
\draw (a) -- (b) node [midway, above] {$f$};
\draw (b) -- (c) \nameandlabel{b}{$g$};
\end{tikzpicture}
\end{document}