如何让 \pgfmathparse 创建四舍五入到小数点后一位的值?

如何让 \pgfmathparse 创建四舍五入到小数点后一位的值?

我尝试在图像上放置网格,以便将其他对象放置在图像上我想要的位置。但是,我无法tikz按我的意愿显示坐标。

这是我的 MWE:

\documentclass{article}
\usepackage[margin=1in]{geometry}
\usepackage{tikz}
\usepackage{graphicx}

\begin{document}

\noindent 
\begin{tikzpicture}
  \node[anchor=south west,inner sep=0pt] (image) at (0,0) {\includegraphics[width=4.5in]{example-image-a}};
  \begin{scope}[x={(image.center |- {(0,0)})},y={(image.center -| {(0,0)})}]
      \draw[help lines,xstep=0.1,ystep=0.1,yellow!20] (0,0) grid (2,2);
      \pgfkeys{/pgf/number format/precision=1}
      \foreach \x in {0,1,...,20} 
        { 
          \pgfmathparse{\x/10};
          \edef\mylabel{\pgfmathresult}
          \node [anchor=north] at (\x/10,0) {\rotatebox{-90}{\mylabel}}; 
        }
  \end{scope}
  \draw[line width=4pt,red] (image.south west) rectangle (image.north east);
\end{tikzpicture}

\end{document}

enter image description here

0.0, 0.1, 0.2, 0.3,...我想要的是获得图像底部边框的 x 值。

我也尝试过以下方法:

\documentclass{article}
\usepackage[margin=1in]{geometry}
\usepackage{tikz}
\usepackage{graphicx}

\begin{document}

\noindent 
\begin{tikzpicture}
  \node[anchor=south west,inner sep=0pt] (image) at (0,0) {\includegraphics[width=4.5in]{example-image-a}};
  \begin{scope}[x={(image.center |- {(0,0)})},y={(image.center -| {(0,0)})}]
      \draw[help lines,xstep=0.1,ystep=0.1,yellow!20] (0,0) grid (2,2);
      \pgfkeys{/pgf/number format/precision=1}
      \foreach \x in {0,0.1,...,2} 
        { 
          \node [anchor=north] at (\x,0) {\rotatebox{-90}{\x}}; 
        }
  \end{scope}
  \draw[line width=4pt,red] (image.south west) rectangle (image.north east);
\end{tikzpicture}

\end{document}

结果是

enter image description here

这次,x 值不仅偏离,而且没有被计算并显​​示2.0

此外,我还尝试过

\node [anchor=north] at (\x,0) {\rotatebox{-90}{\pgfmathprintnumberto[precision=1]{\x}{\myresult}\myresult}}; 

如果我可以四舍五入到小数点后一位或者在任一情况下截断,我会很高兴。 precision但却没有达到我的预期。

有什么建议么?

答案1

您需要\x使用 PGF 数学函数之一处理该值,然后设置\pgfmathresult

enter image description here

\documentclass{article}
\usepackage[margin=1in]{geometry}
\usepackage{tikz}
\usepackage{graphicx}

\begin{document}

\noindent 
\begin{tikzpicture}
  \node[anchor=south west,inner sep=0pt] (image) at (0,0) {\includegraphics[width=4.5in]{example-image-a}};
  \begin{scope}[x={(image.center |- {(0,0)})},y={(image.center -| {(0,0)})}]
      \draw[help lines,xstep=0.1,ystep=0.1,yellow!20] (0,0) grid (2,2);
      \pgfkeys{/pgf/number format/precision=1}
      \foreach \x in {0,0.1,...,2} 
        { 
          \node [anchor=north] at (\x,0) {\rotatebox{-90}{\pgfmathroundtozerofill{\x}\pgfmathresult}}; 
        }
  \end{scope}
  \draw[line width=4pt,red] (image.south west) rectangle (image.north east);
\end{tikzpicture}

\end{document}

上面我已经使用了\pgfmathroundtozerofill{\x}\pgfmathresult}处理\x并将其填充为 1 个零。

相关内容