我定义了一个宏\chooseStyle{text}{styleA}{styleB}
,它根据文本在styleA
和之间进行选择(它只是返回好的样式)。我尝试使用以下方法将其合并到 tikz 样式中:styleB
styleA/.style={...},
styleA/.style={...},
choose/.code={
\tikzset{\chooseStyle{#1}{styleA}{styleB}}
}
但它失败了(就像许多其他尝试一样)并出现错误。出了什么问题?
平均能量损失
\documentclass{article}
\usepackage{amsmath}
\usepackage{etoolbox}
\usepackage{tikz}
\usepackage{tikz-cd}
\usepackage{ifthen}
% Small minus. Feel free to redefine.
\usepackage{amssymb}
\DeclareMathSymbol{\zxMinus}{\mathbin}{AMSa}{"39} % Requires amssymb
\tikzset{
%% Can be redefined by user
% Style for empty nodes
styleA/.style={fill=green},
% Style for nodes that are small enough to fit in a circle, like $\zxMinus \frac{\pi}{4}$
styleB/.style={fill=red},
% Style that chooses which style to apply depending on the input text
choose/.code={
%% Fails (error):
\tikzset{\chooseStyle{#1}{styleA}{styleB}}
%% Fails (error):
% \expandafter\tikzset{\chooseStyle{#1}{styleA}{styleB}}
%% Fails (bad style applied)
% \ifthenelse{\equal{\chooseStyle{#1}{styleA}{styleB}}{styleA}}{\tikzset{styleA}}{\tikzset{styleB}}
},
}
\makeatletter
\newsavebox\zx@box % Temporary box to compute height/width/depth
\NewDocumentCommand{\chooseStyle}{mmm}{%
% #1=text,#2=empty style,#3=other style
\savebox\zx@box{#1}%
% Check if width is 0pt:
\ifdimcomp{\wd\zx@box}{=}{0pt}{% Return empty style if box is empty
#2% Empty style
}{%
#3 % other style
}%
}
\makeatother
\begin{document}
\chooseStyle{}{styleA}{styleB}
\chooseStyle{abc}{styleA}{styleB}
\begin{tikzcd}
\node[choose=]{}; % Should display a green node
\end{tikzcd}
\end{document}