![与 tikzmark 一起使用时 TikZ 输出不正确](https://linux22.com/image/461436/%E4%B8%8E%20tikzmark%20%E4%B8%80%E8%B5%B7%E4%BD%BF%E7%94%A8%E6%97%B6%20TikZ%20%E8%BE%93%E5%87%BA%E4%B8%8D%E6%AD%A3%E7%A1%AE.png)
考虑以下 MWE。代码\mypic
在两个节点之间定位一条线。当我尝试使用\mypic
该tikzmark
库时,线的定位不正确。为什么会发生这种情况,我该如何解决?
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{tikzmark,positioning,calc}
\NewDocumentCommand{\markpic}{m}{\tikz[remember picture]{\node[overlay,above=of pic cs:#1]{\mypic};}}
\NewDocumentCommand{\mypic}{}{
\begin{tikzpicture}
\node[circle=3pt,fill] at (0,0) {};
\draw[] (-.5,-.5) -- (.5,-.5);
\node[circle=3pt,fill] at (0,-1) {};
\end{tikzpicture}
}
\begin{document}
The diagram \tikzmark{C} above is incorrect.
\markpic{C}
\bigskip
The diagram below is correct.
\bigskip
\mypic
\end{document}
答案1
不应嵌套tikzpicture
s。通过将 atikzpicture
放入另一个节点中,tikzpicture
您就是在这样做。如果您将内部存储tikzpicture
在一个盒子中,那么您是安全的。或者,您可以使用 a pic
,但盒子更快。
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{tikzmark,positioning,calc}
\NewDocumentCommand{\markpic}{m}{\tikz[remember picture]{\node[overlay,above=of pic cs:#1]{\mypic};}}
\newsavebox\mypicbox
\sbox\mypicbox{\begin{tikzpicture}
\node[circle=3pt,fill] at (0,0) {};
\draw[] (-.5,-.5) -- (.5,-.5);
\node[circle=3pt,fill] at (0,-1) {};
\end{tikzpicture}}
\NewDocumentCommand{\mypic}{}{\usebox\mypicbox}
\begin{document}
The diagram \tikzmark{C} above is incorrect.
\markpic{C}
\bigskip
The diagram below is correct.
\bigskip
\mypic
\end{document}
如果您确实需要嵌套tikzpicture
s,则需要采取预防措施,确保内部tikzpicture
不使用环境键的某些键。在这种情况下,问题是above
,它将锚点设置为south
。因此圆圈似乎被置换了。或者,您可以避免使用节点作为圆圈,而只填充一些圆圈。(在节点中,键circle
是 的快捷方式shape=circle
,它不带参数,因此与此上下文中circle=3pt
的相同circle
。您可以通过键设置半径inner sep
。)
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{tikzmark,positioning,calc}
\NewDocumentCommand{\markpicA}{m}{\tikz[remember picture]{\node[overlay,above=of pic cs:#1]{\mypicA};}}
\NewDocumentCommand{\markpicB}{m}{\tikz[remember picture]{\node[overlay,above=of pic cs:#1]{\mypicB};}}
\NewDocumentCommand{\mypicA}{}{\begin{tikzpicture}[nodes={anchor=center}]
\node[circle,fill] at (0,0) {};% circle does not options, so "3pt" can be dropped
\draw[] (-.5,-.5) -- (.5,-.5);
\node[circle,fill] at (0,-1) {};
\end{tikzpicture}}
\NewDocumentCommand{\mypicB}{}{\begin{tikzpicture}
\fill[radius=3pt] (0,0) circle;
\draw[] (-.5,-.5) -- (.5,-.5);
\fill[radius=3pt] (0,-1) circle;
\end{tikzpicture}}
\begin{document}
The diagram \tikzmark{C} above is now correct.
\markpicA{C}
\bigskip
The diagram below is correct.
\bigskip
\mypicA
\vspace{4em}
The diagram \tikzmark{D} above is now correct.
\markpicB{D}
\bigskip
The diagram below is correct.
\bigskip
\mypicB
\end{document}