foreach 循环中的节点锚点

foreach 循环中的节点锚点

我需要根据符号更改节点的锚点。例如,如果符号为“-”,则锚点为“北”,否则为“南”。为此,我使用以下方法实现了该函数\def

    \def\side#1{%
        \ifnum#1=-1%
        north%
        \else%
        south%
        \fi%
    }

该解决方案有效,但不一致。我能以某种方式实现它吗TikZ?这个问题甚至可能是全球性的。如何定义一个不返回数值而是返回锚点的函数?也许有一个更好/更紧凑的解决方案。

下面的 MWE


\documentclass[tikz]{standalone}

\begin{document}

\begin{tikzpicture}
    
    \node[draw] (A) at (-1,0) {};
    \node[draw] (B) at (1,0) {};
    
    \def\side#1{%
        \ifnum#1=-1%
        north%
        \else%
        south%
        \fi%
    }
    
    \foreach [evaluate=\i as \j using int(-1*\i)] \i in {-1, 1}
    {
        \draw[->] (A.\side{\i}) -- (B.\side{\j}) ; 
    } 
    
\end{tikzpicture}

\end{document}

答案1

第一个tikzpicture是你的,第二个似乎纯粹基于 TikZ:

\documentclass[tikz]{standalone}

\begin{document}

\begin{tikzpicture}
    
    \node[draw] (A) at (-1,0) {};
    \node[draw] (B) at (1,0) {};
    
    \def\side#1{%
        \ifnum#1=-1%
        north%
        \else%
        south%
        \fi%
    }
    
    \foreach [evaluate=\i as \j using int(-1*\i)] \i in {-1, 1}
    {
        \draw[->] (A.\side{\i}) -- (B.\side{\j}) ; 
    } 
    
\end{tikzpicture}


\begin{tikzpicture}
    
    \node[draw] (A) at (-1,0) {};
    \node[draw] (B) at (1,0) {};
    
    
    
    \foreach [evaluate=\i as \j using int(-1*\i)] \i in {90, 270}
    {
        \draw[->] (A.{\i}) -- (B.{\j}) ; 
    } 
    
\end{tikzpicture}

And the third

\begin{tikzpicture}
    
    \node[draw] (A) at (-1,0) {};
    \node[draw] (B) at (1,0) {};
    
    
    
    \foreach [evaluate=\i as \j using int(-1*\i)] \i in {-1, 1}
    {
        \draw[->] (A.{180+90*\i}) -- (B.{180+90*\j}) ; 
    }



\end{tikzpicture}

\end{document}

在此处输入图片描述

在此处输入图片描述

相关内容