
我有一個複雜的分割形狀,有多個節點部分。我想在節點部分輸入計算值。
當我嘗試使用 \pgfmathsetmacro 執行此操作時,我收到錯誤未定義的控制序列。
這是代碼:
\documentclass[letterpaper, 12 pt] {article}
\usepackage{tikz}
\usetikzlibrary{shapes,calc}
\newcommand{\splitcalcs}[2]{
\pgfmathsetmacro\calcOne{ #2 / #1 }
\pgfmathsetmacro\calcTwo{ \calcOne + #1 }
\nodepart{two}\calcOne
\nodepart{three}\calcTwo
}
\begin{document}
\begin{tikzpicture}
\node (d1)[shape=rectangle split, rectangle split parts=4, fill=red!20, draw] at (4,0)
{Detail 1%
\splitcalcs{8}{4}
};
\end{tikzpicture}
\end{document}
如果我將節點聲明放在命令中,一切都會正常,所以我認為這與評估時間有關,但我不知道如何修復它。
這是有效的(但不是理想的)代碼:
\documentclass[letterpaper, 12 pt] {article}
\usepackage{tikz}
\usetikzlibrary{shapes,calc}
\newcommand{\splitcalcsb}[2]{
\pgfmathsetmacro\calcOne{ #2 / #1 }
\pgfmathsetmacro\calcTwo{ \calcOne + #1 }
\node (d1)[shape=rectangle split, rectangle split parts=4, fill=red!20, draw] at (4,0)
{Detail 1%
\nodepart{two}\calcOne
\nodepart{three}\calcTwo
};
}
\begin{document}
\begin{tikzpicture}
\splitcalcsb{8}{4}
\end{tikzpicture}
\end{document}
答案1
顯然\nodepart
開始了新的單元對齊,之前完成的分配被遺忘了。
\nodepart
您可以在執行之前擴展您需要的部分。我們需要\noexpand
放在前面,\nodepart
以避免其不合時宜的膨脹。
\documentclass[letterpaper, 12pt] {article}
\usepackage{tikz}
\usetikzlibrary{shapes,calc}
\newcommand{\splitcalcs}[2]{%
\pgfmathsetmacro\calcOne{ #2 / #1 }%
\pgfmathsetmacro\calcTwo{ \calcOne + #1 }%
\expanded{%
\noexpand\nodepart{two}\calcOne
\noexpand\nodepart{three}\calcTwo
}%
}
\begin{document}
\begin{tikzpicture}
\node (d1)[shape=rectangle split, rectangle split parts=4, fill=red!20, draw] at (4,0)
{Detail \splitcalcs{8}{4}};
\end{tikzpicture}
\end{document}
請注意,這\expanded
需要一個相當新的 TeX 發行版。你可以用「傳統」方式得到相同的結果:
\begingroup\edef\x{\endgroup
\noexpand\nodepart{two}\calcOne
\noexpand\nodepart{three}\calcTwo
}\x
答案2
對於這些目的xfp
可以得心應手。 (警告:xfp
如果不小心,您不能替換坐標計算,因為 TikZ 區分標量和帶單位的長度。
\documentclass[letterpaper, 12 pt] {article}
\usepackage{xfp}
\usepackage{tikz}
\usetikzlibrary{shapes,calc}
\newcommand{\splitcalcs}[2]{%
\nodepart{two}\fpeval{#2/#1}
\nodepart{three}\fpeval{1+#2/#1}
}
\begin{document}
\begin{tikzpicture}
\node (d1)
[shape=rectangle split, rectangle split parts=4, fill=red!20, draw]
at (4,0)
{Detail 1 \splitcalcs{8}{4}
};
\end{tikzpicture}
\end{document}
答案3
啊哈,問題在於\calcOne
和\calcTwo
是「第一部分」的局部變數。如果你放在\nodepart{one}
開頭,你會得到完全相同的結果。 \nodepart{two}
導致之後的所有內容都放在“第二部分”中,包括\nodepart{three}
(將之後的所有內容放入“第三部分”中)。
\documentclass[letterpaper, 12 pt] {article}
\usepackage{tikz}
\usetikzlibrary{shapes,calc}
\newcommand{\splitcalcs}[2]{%
\pgfmathparse{ #2 / #1 }%
\global\let\calcOne=\pgfmathresult
\pgfmathparse{ \calcOne + #1 }%
\global\let\calcTwo=\pgfmathresult
\nodepart{two}\calcOne
\nodepart{three}\calcTwo
}
\begin{document}
\begin{tikzpicture}
\node (d1)[shape=rectangle split, rectangle split parts=4, fill=red!20, draw] at (4,0)
{Detail%
\splitcalcs{8}{4}};
\end{tikzpicture}
\end{document}