Consider the following example:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning}
\begin{document}
\begin{tikzpicture}
\node (A) {A};
\node (B) [right=2cm of A] {B};
\draw[->,bend left=20] (A) to (B);
\draw[->,bend left=20,red] (B) to (A);
\draw[->,bend right=40,blue] (B) to (A);
\end{tikzpicture}
\end{document}
If I draw the arrow from A to B, then bend left
curves above the height of A and B as expected (the black arrow). But if I reverse the order of the nodes in the path, bend left
curves below A and B (the red arrow).
What I want to do is to always have the arrow above, (like the blue arrow) and not have to specify manually the bend direction. So intuitively, I would like to be able to do the following:
if A is left of B then bend left
else
if B is left of A then bend right
How would I do that?
Best Answer
The actual math it simple, we calculate the difference between start and end point and choose the appropriate bend direction depending on the sign of
\pgf@x
or\pgf@y
. (Though, the special cases for the difference being zero are not considered here.)This also only uses the center of the nodes, if the nodes have different size this might not lead to the correct result.
The implementation below uses PGF to calculate the difference and also a faster approach to using the keys. With the
calc
library, the math can be done with thelet
operation:The direct usage of
\tikz@to@curve@path
allows us to avoid nestingto
paths which needs some special expansion control otherwise to avoid recursive definitions like\def\tikztotarget{\tikztotarget}
andto
nodes to be lost or not applies correctly:Code
Output