Tikz:取决于内容宽度/高度的条件样式

Tikz:取决于内容宽度/高度的条件样式

我想根据内部文本的高度/宽度应用不同的样式(当然在应用任何样式之前):

在此处输入图片描述

目前我定义了 3 种样式,但我不确定如何访问节点的内容(或者为什么不直接访问节点内容的高度/宽度)。

平均能量损失

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{backgrounds,positioning}
\usetikzlibrary{shapes,shapes.geometric,shapes.misc}

\begin{document}

\tikzset{
  nodeEmpty/.style={minimum width=.3mm, circle, fill=green},
  nodeSmall/.style={minimum width=.3mm, circle, fill=green!70!black},
  nodeLong/.style={minimum width=1cm, rounded rectangle, fill=green!50!black, inner xsep=3mm},
  nodeAuto/.code={
    %%% Goal: apply automatically the good style depending on the width of the text inside. Something like: if empty, apply nodeEmpty, if height is smaller than 2em and if ratio height/width > 0.5, apply nodeSmall, else apply nodeLong.
    % ???
  }
}

\begin{tikzpicture}
  \node[nodeEmpty] at (0,0) {};
  \node[nodeSmall] at (2,0) {$\frac{\pi}{2}$};
  \node[nodeLong] at (4,0) {$a+b+c+d$};
\end{tikzpicture}

\end{document}

答案1

正如所建议的,可以定义一个用于以下目的的命令:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{backgrounds,positioning}
\usetikzlibrary{shapes,shapes.geometric,shapes.misc,math,calc}

\begin{document}

\tikzset{
  nodeEmpty/.style={minimum width=.3mm, circle, fill=green},
  nodeSmall/.style={minimum width=.3mm, circle, fill=green!70!black},
  nodeLong/.style={minimum width=1cm, rounded rectangle, fill=green!50!black, inner xsep=3mm},
  nodeAuto/.code={
    %%% Goal: apply automatically the good style depending on the width of the text inside. Something like: if empty, apply nodeEmpty, if height is smaller than 2em and if ratio height/width > 0.5, apply nodeSmall, else apply nodeLong.
    % ???
  }
}
\newcommand{\NodeWithVariableStyle}[2]{\tikzmath{ 
        if width("#2") == 0
        then {let \st=nodeEmpty;}
        else {if height("#2") < scalar(2em)&&
            height("#2")/width("#2") > 0.5
            then {let \st=nodeSmall;}
            else {let \st=nodeLong;};
        };
        {
            \node[\st] at #1 {#2}; 
        }; 
}}%\NodeWithVariableStyle{position}{content}
\begin{tikzpicture}

  \NodeWithVariableStyle{(0,0)}{}
  \NodeWithVariableStyle{(2,0)}{$\frac{\pi}{2}$}
  \NodeWithVariableStyle{(4,0)}{$a+b+c+d$}

\end{tikzpicture}
\end{document}

具有可变样式的节点

相关内容