我有以下代码,其中两个节点通过箭头连接:
\documentclass[crop,tikz]{standalone}
\begin{document}
\usetikzlibrary{positioning,calc}
\tikzstyle{block} = [draw, rectangle, minimum height=1cm, minimum width=1cm]
\tikzstyle{halfblock} = [draw, rectangle, minimum height=0.5cm, minimum width=1cm]
\begin{tikzpicture}
\node [block,align=center](A) {A};
\node [halfblock,align=center,above right=-0.5cm and 1cm of A](B) {B};
\draw [->] ($(A.east) + (0,0.25cm)$)--(B.west);
\end{tikzpicture}
\end{document}
较小的块 B 的高度应该恰好是较大块 A 的高度的一半。
但是,当我像上面所示那样连接这些块时,箭头不是完全笔直的,而是有一点点倾斜。此外,两个块的上边框没有对齐,尽管从它们的大小来看它们应该对齐。这里是输出图像:
正如您所见,箭头不是 100% 笔直。
问题:我该如何修复这个问题?
答案1
请尝试以下操作:
\documentclass[crop,tikz]{standalone}
\usetikzlibrary{positioning,calc}
\begin{document}
\tikzset{
block/.style = {draw, rectangle, minimum size=1cm},
halfblock/.style = {draw, rectangle, minimum height=0.5cm, minimum width=1cm}
}
\begin{tikzpicture}
\node [block](A) {A};
\node [halfblock,align=center,above right=-0.5cm and 1cm of A](B) {B};
\draw [->] (A.east |- B) -- (B); % <---
\end{tikzpicture}
\end{document}
变化表示% <---
或者您可能正在寻找以下内容:
为了得到这个结果你应该添加到每个节点样式定义outer sep=0pt
或者例如定义通用样式,其中包含选项outer sep=0pt
:
\documentclass[crop,tikz]{standalone}
\usetikzlibrary{positioning}
\begin{document}
\tikzset{
base/.style = {draw, align=center, % <---
outer sep=0pt}, % <---
block/.style = {base,minimum size=1cm},
halfblock/.style = {base, minimum height=0.5cm, minimum width=1cm}
}
\begin{tikzpicture}
\node [block](A) {A};
\node [halfblock,above right=-0.5cm and 1cm of A](B) {B};
\draw [->] (A.east |- B) -- (B); % <---
\end{tikzpicture}
\end{document}
答案2
如果您希望上部线条具有相同的 y 值,则可以使用适当的锚点。此过程的优点是,如果高度超过最小值,它仍将有效。
\documentclass[crop,tikz]{standalone}
\begin{document}
\tikzset{block/.style={draw, rectangle, minimum height=1cm, minimum width=1cm},
halfblock/.style={draw, rectangle, minimum height=0.5cm, minimum width=1cm}}
\begin{tikzpicture}
\node [block,align=center](A) {A};
\node [halfblock,align=center,anchor=north west] (B) at ([xshift=1cm]A.north
east) {B};
\draw [<-] (B.west) -- (A.east |-B.west);
\end{tikzpicture}
\end{document}