我最近开始使用 tikz,发现可以使用chain
和fit
库链接节点并嵌套它们。我已经成功完成了这两项工作:
合身:
\begin{tikzpicture}[node distance = 12mm and 0mm, start chain=c1 going below]
\node [draw=black!50] (content1) {
Some text
};
\node [draw=black!50, below=0mm of content1.south] (content2) {
Some text
};
\node [draw=black!50, fit={(content1) (content2)}] (box1) {};
\end{tikzpicture}
链:
\begin{tikzpicture}[node distance = 12mm and 0mm, start chain=c1 going below]
\node [draw=black!50, on chain=c1] (content1) {
Some text
};
\node [draw=black!50, on chain=c1] (content2) {
Some text
};
\end{tikzpicture}
但是,当我将它们组合起来时:
\begin{tikzpicture}[node distance = 12mm and 0mm, start chain=c1 going below]
\node [draw=black!50] (content1) {
Some text
};
\node [draw=black!50] (content2) {
Some text
};
\node [draw=black!50, fit={(content1)}, on chain=c1] (box1) {};
\node [draw=black!50, fit={(content2)}, on chain=c1] (box2) {};
\end{tikzpicture}
链接在嵌套节点上不起作用:
我希望链接能够在层次结构上工作,这样如果框节点被链接起来,它们将带上内容节点。我制作了一个硬编码示例,说明我希望它在这里看起来如何:
\begin{tikzpicture}[node distance = 12mm and 0mm, start chain=c1 going below]
\node [draw=black!50] (content1) {
Some text
};
\node [draw=black!50, below=of content1, yshift=-2.5mm] (content2) {
Some text
};
\node [draw=black!50, fit={(content1)}] (box1) {};
\node [draw=black!50, fit={(content2)}, below=of box1] (box2) {};
\end{tikzpicture}
我的问题是:是否可以动态实现,使得内容节点彼此不了解?
答案1
这是您想要实现的吗?我认为,您应该首先使用 将节点放置在链上on chain
,然后使用fit
将其他节点放置在链上的节点上:
\documentclass[border=10mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{chains,fit}
\begin{document}
\begin{tikzpicture}[node distance=12mm and 0mm, start chain=c1 going below]
\node [draw=black!50, on chain=c1] (content1) {
Some text
};
\node [draw=black!50, on chain=c1] (content2) {
Some text
};
\node [draw=black!50, fit={(content1)}] (box1) {};
\node [draw=black!50, fit={(content2)}] (box2) {};
\end{tikzpicture}
\end{document}
使用fit
节点,您可以根据需要包裹任意数量的其他节点,它将根据包裹节点的大小自动调整大小:
\documentclass[border=10mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{chains,fit}
\begin{document}
\begin{tikzpicture}[node distance=12mm and 0mm, start chain=c1 going below]
\node [draw=black!50, on chain=c1] (content1) {
Some text
};
\node [draw=black!50, on chain=c1] (content2) {
Some text
};
\node [draw=black!50, on chain=c1, align=center] (content3) {
Some longer text \\ over two lines
};
\node [draw=black!50, fit={(content1)}] (box1) {};
\node [draw=black!50, fit={(content2) (content3)}] (box2) {};
\end{tikzpicture}
\end{document}
答案2
节点fit
只是一个根据其他节点计算其尺寸的节点。 而chain
只是一种绘制节点的方法,可以更轻松地定位它们。
Amatrix
是包含其他节点的节点。这是将多个节点放在一起的一种选择。但您不能嵌套matrix
节点。尽管您可以使用 fit 连接多个矩阵节点。
\documentclass[tikz, border=2mm]{standalone}
\usetikzlibrary{matrix, fit, positioning}
\begin{document}
\begin{tikzpicture}[mymat/.style={matrix of nodes, draw, nodes={draw, anchor=center}, row sep=1pt}]
\matrix[mymat] (A) {
Some text\\
Some more text\\};
\matrix[mymat, below=of A] (B){
Some text & More text\\
Some more text\\};
\node[draw, fit=(A) (B)]{};
\end{tikzpicture}
\end{document}