declare function
在 的条件下如何使用 a \foreach
?这是我的 MWE:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[declare function={a = 0; b = 5;}]
\foreach \x in {{a},...,{b}}{
\draw (\x,0) -- (0,\x);
}
\end{tikzpicture}
\end{document}
这让我
Missing number, treated as zero.
(第 10 行,循环的结束括号)。
人们甚至可以在后面的选项[options list]
中使用声明的函数,但为什么不简单地在里面呢?tikzpicture
declare function
\foreach
答案1
您可以先评估表达式:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[declare function={a=0;b = 5;}]
\pgfmathparse{{a}}\let\pgfmathresulta\pgfmathresult
\pgfmathparse{{b}}\let\pgfmathresultb\pgfmathresult
\foreach \x in {\pgfmathresulta,...,\pgfmathresultb}{
\draw (\x,0) -- (0,\x);
}
\end{tikzpicture}
\end{document}
答案2
这段小代码添加了两个可选使用的键\foreach
:
use int
和use float
我让例子来说明一切:
\begin{tikzpicture}[declare function={a = 0; b = 5;}]
\foreach \x[use int=a to b] \draw (\x,0) -- (0,\x);
\end{tikzpicture}
\begin{tikzpicture}
\foreach \x[use int=2 to 10 step 2] {
\ifnum\x=\foreachEnd
\tikzset{every path/.append style=thick}
\fi
\draw (\x/2,0) -- (0,\x/3);
}
\end{tikzpicture}
免责声明:不提供任何担保;很可能下一刻就会失效。
代码
\documentclass[tikz]{standalone}
\usepackage{tikz}
\makeatletter
\newif\ifqrr@pgf@foreach@no@list
\pgfkeys{
/pgf/foreach/.cd,
@use/.code args={#1to#2}{%
\qrr@pgf@foreach@no@listtrue
\qrr@pgf@foreach@no@list@use\foreachStart{#1}%
\pgfutil@in@{step}{#2}
\ifpgfutil@in@
\qrr@pgf@foreach@no@list@parse@step#2\pgffor@stop
\else
\qrr@pgf@foreach@no@list@parse@step#2step1\pgffor@stop
\fi
\edef\qrr@pgf@foreach@no@list@list{\foreachStart,\foreachSecond,...,\foreachEnd}},
use int/.code={%
\let\qrr@pgf@foreach@no@list@use\pgfmathtruncatemacro
\pgfkeysalso{/pgf/foreach/@use={#1}}%
},
use float/.code={%
\let\qrr@pgf@foreach@no@list@use\pgfmathsetmacro
\pgfkeysalso{/pgf/foreach/@use={#1}}%
}
}
\def\qrr@pgf@foreach@no@list@parse@step#1step#2\pgffor@stop{%
\qrr@pgf@foreach@no@list@use\foreachEnd{#1}%
\qrr@pgf@foreach@no@list@use\foreachSecond{\foreachStart+#2}%
}
\def\pgffor@vars{% manually extended, better etoolbox
\pgfutil@ifnextchar i{\pgffor@@vars@end}{%
\pgfutil@ifnextchar[{\pgffor@@vars@opt}{%]
\pgfutil@ifnextchar/{\pgffor@@vars@slash@gobble}{%
\ifqrr@pgf@foreach@no@list\expandafter\pgfutil@firstoftwo\else
\expandafter\pgfutil@secondoftwo\fi
{\qrr@pgf@foreach@no@listfalse\pgffor@macro@list\qrr@pgf@foreach@no@list@list}
{\pgffor@@vars}}}}}%
\makeatother
\begin{document}
\begin{tikzpicture}[declare function={a = 0; b = 5;}]
\foreach \x[use int=a to b] \draw (\x,0) -- (0,\x);
\end{tikzpicture}
\begin{tikzpicture}
\foreach \x[use int=2 to 10 step 2] {
\ifnum\x=\foreachEnd
\tikzset{every path/.append style=thick}
\fi
\draw (\x/2,0) -- (0,\x/3);
}
\end{tikzpicture}
\end{document}