如何在 \tikzset 中添加条件?

如何在 \tikzset 中添加条件?

我正在尝试进行一些修改Andrew Stacey 的回答我之前的问题“在 TikZ 中绘制具有几个参数的矩形的宏”。

当前代码如下:

\documentclass{article}
\usepackage[frenchb]{babel}
\usepackage{tikz}
\usetikzlibrary{fit}

\tikzset{
  my funny rectangle/.style n args={4}{%
    rectangle,
    draw,
    append after command={\pgfextra{\let\mainnode=\tikzlastnode}
      node[above right] at (\mainnode.north west) {#3}%
      node[above left] at (\mainnode.north east) {#4}%
      node[below left] at (\mainnode.north west) {#1}%
      node[above left] at (\mainnode.south west) {#2}%
    },
  }
}

\begin{document}
\begin{tikzpicture}
\node[my funny rectangle={1}{7}{4}{8}] {a text};
\node[my funny rectangle={$i$}{$i$}{4}{8}, text width={3cm}, minimum height={3cm}, text centered] (abc) at (5,5) {text};
\end{tikzpicture}
\end{document}

我想在里面添加一个条件append after command:if #1= #2,do only node[below left] at (\mainnode.west) {#1},else do node[below left] at (\mainnode.north west) {#1}and node[above left] at (\mainnode.south west) {#2}

@Werner 建议的答案对于像 这样的参数很有效{1}{7}{4}{8},但对于 这样的参数无效{$i$}{$i$}{4}{8}。有人有想法吗?

答案1

这可能就是你想要的:

在此处输入图片描述

\ifx#1#2 <true> \else <false> \fi在这种情况下,标准 TeX 条件起作用,执行<true>if #1=#2否则执行<false>

\documentclass{standalone}
%\url{http://tex.stackexchange.com/q/27278/86}
\usepackage{tikz}
\usetikzlibrary{fit}

\tikzset{
  my funny rectangle/.style n args={4}{%
    rectangle,
    draw,
    fit={(#3,#1) (#4,#2)},
    append after command={\pgfextra{\let\mainnode=\tikzlastnode}
      node[above right] at (\mainnode.north west) {#3}%
      node[above left] at (\mainnode.north east) {#4}%
      \ifx#1#2
        node[left] at (\mainnode.west) {#1}%
      \else
        node[below left] at (\mainnode.north west) {#1}%
        node[above left] at (\mainnode.south west) {#2}%
      \fi
    },
  }
}

\begin{document}
\begin{tikzpicture}
  \node[my funny rectangle={1}{1}{4}{8}] {text};
\end{tikzpicture}
\end{document}

编辑:以下是更新后的代码,它解决了向传递一些非数字参数的问题my funny rectangle。由于节点不再是fitted,因此您需要指定其他宽度和高度参数:

在此处输入图片描述

\documentclass{article}
\usepackage{tikz}% http://ctan.org/pkg/pgf
%\usetikzlibrary{fit}

\tikzset{
  my funny rectangle/.style n args={4}{%
    rectangle,
    draw,
    %fit={(#3,#1) (#4,#2)},
    append after command={\pgfextra{%
      \let\mainnode=\tikzlastnode%
      \def\argone{#1}\def\argtwo{#2}}
      node[above right] at (\mainnode.north west) {#3}%
      node[above left] at (\mainnode.north east) {#4}%
      \ifx\argone\argtwo
        node[left] at (\mainnode.west) {#1}%
      \else
        node[below left] at (\mainnode.north west) {#1}%
        node[above left] at (\mainnode.south west) {#2}%
      \fi
    },
  }
}

\begin{document}
\begin{tikzpicture}
\node[my funny rectangle={$i$}{$i$}{4}{8}, text width={3cm}, minimum height={3cm}, text centered] (abc) at (5,5) {text};
\end{tikzpicture}
\end{document}

相关内容