![装饰中节点的 rnd 最小宽度在重复代码中大小不一致](https://linux22.com/image/453056/%E8%A3%85%E9%A5%B0%E4%B8%AD%E8%8A%82%E7%82%B9%E7%9A%84%20rnd%20%E6%9C%80%E5%B0%8F%E5%AE%BD%E5%BA%A6%E5%9C%A8%E9%87%8D%E5%A4%8D%E4%BB%A3%E7%A0%81%E4%B8%AD%E5%A4%A7%E5%B0%8F%E4%B8%8D%E4%B8%80%E8%87%B4.png)
我想用双行星星装饰路径,并希望上行星星与下行星星重复。但为什么部分星星state{initial}
仍然是随机大小。
我尝试设置最小宽度,但它给出的星星都相同。
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{decorations,shapes.geometric,decorations.shapes,decorations.pathmorphing}
\begin{document}
\begin{tikzpicture}
\pgfdeclaredecoration{stars}{initial}{
\state{initial}[width=15pt ] {
\pgfmathparse{round(rnd*100)}
\pgfsetfillcolor{yellow!\pgfmathresult!orange}
\pgfsetstrokecolor{yellow!\pgfmathresult!red}
% set node mininum width
%\pgfmathparse{\pgfkeysvalueof{/pgf/minimum width} }
%\pgfset{minimum width=\pgfmathresult pt }
\pgfnode{star}{center}{}{}{\pgfusepath{stroke,fill}} % line lower stars
\pgftransformshift{\pgfpoint{0pt}{12pt}}
\pgfnode{star}{center}{}{}{\pgfusepath{stroke,fill}} % line upper stars
}
\state{final} {
\pgfpathmoveto{\pgfpointdecoratedpathlast}
}
}
\draw[decorate, decoration={stars}, star point ratio=2, star points=5, inner sep=0, minimum width=rnd*10pt+2pt] (0,0) -- +(5,0);
\end{tikzpicture}
\end{document}
答案1
如果需要多次访问 PGF 计算的结果,最好使用 将其存储在宏中\pgfmathtruncatemacro
。这也是存储\pgfkeysvalueof{/pgf/minimum width}
在宏中的正确方法。
需要这两行来使上方和下方的星星具有相同的大小:
\pgfmathtruncatemacro{\myresultB}{\pgfkeysvalueof{/pgf/minimum width}}
\pgfset{minimum width=\myresultB}
由于您想设置minumum width
为某个随机值,因此您需要防止 Ti钾Z 多次计算该值。这是通过上面的两行代码完成的,其中minimum width
内部设置为计算出的随机值,当将其应用于两颗星星时,它将保持该值固定。
\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric, decorations.shapes}
\pgfdeclaredecoration{stars}{initial}{
\state{initial}[width=15pt] {
\pgfmathtruncatemacro{\myresultA}{round(rnd*100)}
\pgfsetfillcolor{yellow!\myresultA!orange}
\pgfsetstrokecolor{yellow!\myresultA!red}
% set node mininum width
\pgfmathtruncatemacro{\myresultB}{\pgfkeysvalueof{/pgf/minimum width}}
\pgfset{minimum width=\myresultB}
\pgfnode{star}{center}{}{}{\pgfusepath{stroke,fill}} % line lower stars
\pgftransformshift{\pgfpoint{0pt}{12pt}}
\pgfnode{star}{center}{}{}{\pgfusepath{stroke,fill}} % line upper stars
}
\state{final} {
\pgfpathmoveto{\pgfpointdecoratedpathlast}
}
}
\begin{document}
\begin{tikzpicture}
\draw[decorate, decoration={stars}, star point ratio=2, star points=5, inner sep=0, minimum width={rnd*10pt+2pt}] (0,0) -- +(5.5,0);
\end{tikzpicture}
\end{document}