![根据条件在 tikzpicture 中相对定位节点](https://linux22.com/image/455602/%E6%A0%B9%E6%8D%AE%E6%9D%A1%E4%BB%B6%E5%9C%A8%20tikzpicture%20%E4%B8%AD%E7%9B%B8%E5%AF%B9%E5%AE%9A%E4%BD%8D%E8%8A%82%E7%82%B9.png)
\begin{tikzpicture}[node distance={20mm}, thick, main/.style = {draw, ellipse}]
\node[main] (0) {0};
\node[main, below=10mm of 0] (1) {1};
\node[main, below=10mm of 1] (2) {2};
\node[main, right=10mm of 1] (3) {3};
\node[main,\ifthenelse{1>0}{above}{below}=10mm of 3] (4) {4};
\end{tikzpicture}
我想根据条件将节点 4 放置在节点 3 的上方或下方。我该如何实现?到目前为止,我只收到以下错误消息:
\XC@definec@lor 的参数有一个额外的}。...\ifthenelse{1>0}{above}{below}=10mm of 3]
答案1
受到IfValueTF
tcolorbox 的 key 的启发,您可以创建如下内容:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning,shapes}
\usepackage{ifthen}
\tikzset{
ifthen/.code n args={3}{
\ifthenelse{#1}{\pgfkeysalso{#2}}{\pgfkeysalso{#3}}
}
}
\begin{document}
\begin{tikzpicture}[node distance={20mm}, thick, main/.style = {draw, ellipse}]
\node[main] (0) {0};
\node[main, below=10mm of 0] (1) {1};
\node[main, below=10mm of 1] (2) {2};
\node[main, right=10mm of 1] (3) {3};
\node[
main,
ifthen={1<0}{above=10mm of 3}{below=10mm of 3}
] (4) {4};
\end{tikzpicture}
\end{document}
答案2
这个例子有效。(带包ifthen
)
\documentclass[12pt,a4paper]{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\usetikzlibrary{shapes.geometric}
\usepackage{ifthen}
\begin{document}
\textbf{\#4 above \#3}\medskip
\newcommand{\z}{0}
\begin{tikzpicture}[node distance={20mm}, thick, main/.style = {draw, ellipse}]
\node[main] (0) {0};
\node[main, below=10mm of 0] (1) {1};
\node[main, below=10mm of 1] (2) {2};
\node[main, right=10mm of 1] (3) {3};
\ifthenelse{1>\z}{\node[main,above=10mm of 3] (4) {4};}{\node[main,below=10mm of 3] (4) {4};}
\end{tikzpicture}
\bigskip
\textbf{\#4 below \#3}\medskip
\renewcommand{\z}{2}
\begin{tikzpicture}[node distance={20mm}, thick, main/.style = {draw, ellipse}]
\node[main] (0) {0};
\node[main, below=10mm of 0] (1) {1};
\node[main, below=10mm of 1] (2) {2};
\node[main, right=10mm of 1] (3) {3};
\ifthenelse{1>\z}{\node[main,above=10mm of 3] (4) {4};}{\node[main,below=10mm of 3] (4) {4};}
\end{tikzpicture}
\end{document}