我想在矩阵中插入的某些节点中自动插入一些文本,因此我使用execute at begin node
。但不幸的是,节点向上移动并且不再对齐:
知道如何修复它吗?
谢谢!
梅威瑟:
\documentclass[tikz]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}[remember picture,
box/.style={
draw,
minimum height=10mm,
minimum width=3cm,
fill=green!50,
},
boxA/.style={
box,
execute at begin node={A},
},
emptyBox/.style={box},
]%
\matrix [matrix of nodes,row sep=1cm, column sep=1cm]
{
|[boxA]| & |[emptyBox]| \\
|[boxA]| & |[emptyBox]| \\
};
\end{tikzpicture}%
\end{document}
-- 编辑 -- 哦,我刚刚意识到这不仅仅是因为execute at begin node
,但任何文本都会使它发生变化……出了什么问题?
答案1
实际上我们只需要设置anchor=center
为框(或者手动指定text depth
/ text height
,感谢 hrnz):
\documentclass[tikz]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}[remember picture,
box/.style={
draw,
anchor=center,
minimum height=10mm,
minimum width=3cm,
fill=green!50,
},
boxA/.style={
box,
execute at begin node={A},
},
emptyBox/.style={box},
]%
\matrix [matrix of nodes,row sep=1cm, column sep=1cm]
{
|[boxA]| & |[emptyBox]| \\
|[boxA]| & |[emptyBox]| \\
};
\end{tikzpicture}%
\end{document}
答案2
您的问题您自己在回答中解决了(+1),因此仅需一些注释:
- 您可能出于某些原因而选择使用选项,
execute at begin node
而不是直接在矩阵单元格中插入所需单元格的内容。稍后会给出更简单的代码:
\documentclass[tikz, margin=3mm]{standalone}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}
\matrix [matrix of nodes,
nodes in empty cells, % new
nodes={draw, fill=green!50, anchor=center, % new
minimum width=30mm, minimum height=10mm}, % new
row sep=1cm, column sep=1cm]
{
A & \\
A & \\
};
\end{tikzpicture}
\end{document}
- 如果单元格内容较长,则结合使用
execute at begin node
上例中的方法和矩阵的单元格样式可能会更有意义。例如:
\documentclass[tikz, margin=3mm]{standalone}
\usetikzlibrary{matrix}
\begin{document}
\begin{tikzpicture}[
cA/.style={execute at begin node={$E=mc^2$}}, % modified your approach
]
\matrix [matrix of nodes,
nodes in empty cells,
nodes={draw, fill=green!50, anchor=center,
minimum width=30mm, minimum height=10mm},
row sep=1cm, column sep=1cm]
{
|[cA]| & \\
|[cA]| & \\
};
\end{tikzpicture}%
\end{document}