我有一张 tikz 图片,我想在其中绘制一个从节点中包含的表格中的单元格到另一个节点的锚点的箭头:(使用 Microsoft Paint 添加箭头)
我尝试使用 来绘制箭头tikzmark
,据我所知,它在 之外完美运行tikzpicture
:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning, tikzmark}
\begin{document}
\begin{tikzpicture}[font = \ttfamily]
\node (s) {
\begin{tabular}{|c|c|}
\hline
ptr & \tikzmark{s ptr} \\
\hline
len & 5 \\
\hline
\end{tabular}
};
\node [right = of s.north east] (content north west) {};
\node [below right] (content) at (content north west) {
\begin{tabular}{|c|c|}
\hline
"hello" \\
\hline
\end{tabular}
};
\draw [->] (s ptr) -- (content.west);
\end{tikzpicture}
\end{document}
只会遇到一个令人费解的错误:
! Package tikz Error: Cannot parse this coordinate.
See the tikz package documentation for explanation.
Type H <return> for immediate help.
...
l.12 ptr & \tikzmark{s ptr} \\
不清楚该怎么做,我\tikzmark
改为\tikzmarknode
:
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{positioning, tikzmark}
\begin{document}
\begin{tikzpicture}[font = \ttfamily]
\node (s) {
\begin{tabular}{|c|c|}
\hline
ptr & \tikzmarknode{s ptr}{} \\
\hline
len & 5 \\
\hline
\end{tabular}
};
\node [right = of s.north east] (content north west) {};
\node [below right] (content) at (content north west) {
\begin{tabular}{|c|c|}
\hline
"hello" \\
\hline
\end{tabular}
};
\draw [->] (s ptr) -- (content.west);
\end{tikzpicture}
\end{document}
这消除了错误。然而,在多次编译代码后,箭头一直在奇怪的地方移动,最后收敛到:
这是不可取的。
目前,我通过对坐标进行硬编码来解决这个问题(s.north east) - (10pt, 10pt)
。有没有更优雅的解决方案来解决这个问题?
答案1
使用这些matrix
库很简单:
\documentclass[tikz, margin=3mm]{standalone}
\usetikzlibrary{arrows.meta,
matrix,
positioning}
\begin{document}
\begin{tikzpicture}[
every node/.append style = {minimum size=1.5em,
inner sep=1mm, outer sep=0mm,
font=\sffamily}
]
\node (m) [matrix of nodes,
nodes in empty cells,
nodes= {anchor=center},
column sep=-\pgflinewidth,
row sep=-\pgflinewidth,
draw,
inner sep=0pt
]
{
ptr & \\
length & 5 \\
};
\draw (m.west) -- (m.east)
(m-1-2.north -| m-2-1.east) -- (m-2-2.south west);
\node [draw, right = of m-1-2.east] (n) {"hello"};
%
\draw [-Straight Barb] (m-1-2.center) -- (n);
\end{tikzpicture}
\end{document}
附录:没有办法添加具有\hline
已知特征的线条和垂直线。但是,可以这样做半自动,这意味着您不需要单独绘制它们,但是您需要使用minimum width
任意一列中的单元格来确定列宽:
\documentclass[tikz, margin=3mm]{standalone}
\usetikzlibrary{arrows.meta,
matrix,
positioning}
\begin{document}
\begin{tikzpicture}[
every node/.append style = {draw, minimum size=1.5em,
inner sep=1mm, outer sep=0mm,
font=\sffamily}
]
\node (m) [matrix of nodes,
nodes in empty cells,
nodes= {anchor=center},
column sep=-\pgflinewidth,
row sep=-\pgflinewidth,
column 1/.append style = {nodes={minimum width=4em}}, % width of the wides cell in column 2
column 2/.append style = {nodes={minimum width=2em}}, % with of the widest cell in column 2
draw,
inner sep=0pt
]
{
ptr & \\
length & 5 \\
};
\node [draw, right = of m-1-2.east] (n) {"hello"};
%
\draw [-Straight Barb] (m-1-2.center) -- (n);
\end{tikzpicture}
\end{document}
@leandriis 在他的评论中也提出了类似的解决方案。