提问于:
浏览数:
2436
```tex
\documentclass[tikz]{standalone}
\usetikzlibrary{fit}
\tikzset{%
pics/abc/.style={%
code={
\node {this is some path};
}
}
}
\begin{document}
\begin{tikzpicture}
%fit失败
\foreach \i in {1,...,3} \pic[local bounding box=a\i] at (0,\i) {abc};
\node[draw,fit={(a1)(a2)(a3)}] {};
%fit成功
\pic[local bounding box=a4] at (10,4) {abc};
\pic[local bounding box=a5] at (10,5) {abc};
\pic[local bounding box=a6] at (10,6) {abc};
\node[draw,fit={(a4)(a5)(a6)}] {};
\end{tikzpicture}
\end{document}
```
请问在保留`foreach`语句的条件下,如何让`(a1)(a2)(a3)`成功被`fit`?
3 回答
0
根据tex stack exchange 上的回答[tex sc](https://tex.stackexchange.com/questions/533786/failed-to-use-the-local-bounding-box-produced-by-foreach-and-pic),需要用到`/.expanded`将`\i`完全展开
```tex
\documentclass[tikz]{standalone}
\usetikzlibrary{fit}
\tikzset{%
pics/abc/.style={%
code={
\node {this is some path};
}
}
}
\begin{document}
\begin{tikzpicture}
%fit失败
\foreach \i in {1,...,3} \pic[local bounding box/.expanded=a\i] at (0,\i) {abc};
\node[draw,fit={(a1)(a2)(a3)}] {};
%fit成功
\pic[local bounding box=a4] at (10,4) {abc};
\pic[local bounding box=a5] at (10,5) {abc};
\pic[local bounding box=a6] at (10,6) {abc};
\node[draw,fit={(a4)(a5)(a6)}] {};
\end{tikzpicture}
\end{document}
```
-
非常感谢! – zhaochongbin 2020-04-09 16:17 回复
0
一个“治标”的解决方法是,在循环里面用`node`把`pic`套起来,就可以在外部通过`fit` `node`名称,从而间接`fit` `pic`了。缺点是,会多了默认的`inner sep=.333em`,需要人为取消。
```tex
\documentclass[tikz]{standalone}
\usetikzlibrary{fit}
\tikzset{
pics/abc/.style={
code={
\node {this is some path};
}
}
}
\begin{document}
\begin{tikzpicture}
\foreach \i in {1,...,3} {
\pic[local bounding box=a\i] at (0,\i) {abc};
\node[fit=(a\i),local bounding box=Az\i] (A\i) {};
}
\node[draw,fit={(A1)(A2)(A3)}] {};
\pic[local bounding box=a4] at (4,1) {abc};
\pic[local bounding box=a5] at (4,2) {abc};
\pic[local bounding box=a6] at (4,3) {abc};
\node[draw,fit={(a4)(a5)(a6)}] {};
\foreach \i in {1,...,3} {
\pic[local bounding box=b\i] at (8,\i) {abc};
\node[fit=(b\i),inner sep=0pt] (B\i) {};
}
\node[draw,fit={(B1)(B2)(B3)}] {};
\end{tikzpicture}
\end{document}
```
![](https://pics.latexstudio.net/data/images/202003/f6efe150db83f50.png)
另外,若`foreach`中的`node`也用`local bounding box`命名,同样无法被`fit`,即
```tex
%fit失败
\foreach \i in {1,...,3} \node[local bounding box=a\i] at (0,\i) {};
\node[draw,fit={(a1)(a2)(a3)}] {};
%fit成功
\foreach \i in {1,...,3} \node (a\i) at (0,\i) {};
\node[draw,fit={(a1)(a2)(a3)}] {};
```
0
```tex
\tikzset{
seagull/.pic={
\draw (-3mm,0) to [bend left] (0,0) to [bend left] (3mm,0);
}
}
\tikz{
\foreach \i in {1,2,3}{
\pic [local bounding box={a\i},] at(0,\i) {seagull};
}
}
\ifcsname pgf@sh@ns@a1\endcsname
yes
\else
no
\fi
\csname pgf@sh@np@a1\endcsname
\meaning\southwest
```
看一下这段代码的执行结果就知道为什么会 fit 失败了。原因跟 **pgfplotstable** 手册(1.16版)的最后一页的例子一样。
从你的代码看,你可能需要 `current path bounding box` 这个预定义 node.
你的回答
请登录后回答
你的回答将会帮助更多人,请务必认真回答问题。