TIKZ 宏用于绘制百分之一正方形

TIKZ 宏用于绘制百分之一正方形

如果我指定数字 195,我想使用宏来自动绘制它。

\begin{tikzpicture}[scale=0.25,baseline={([yshift=-.5ex]current bounding box.center)}]
        \foreach \i in {0,...,9}{
            \foreach \j in {0,...,9}{
                \draw[red,shift={(\i,\j)},fill](0,0) rectangle (1,1);
        }}


        \foreach \i in {0,...,9}{
            \foreach \j in {0,...,9}{
                \draw[shift={(\i,\j)}](0,0) rectangle (1,1);
        }}
        \draw[very thick] (0,0) rectangle (10,10);
        \end{tikzpicture}
        \begin{tikzpicture}[scale=0.25,baseline={([yshift=-.5ex]current bounding box.center)}]
        \foreach \i in {0,...,8}{
            \foreach \j in {0,...,9}{
                \draw[red,shift={(\i,\j)},fill](0,0) rectangle (1,1);
        }}

        \foreach \j in {5,...,9}{
            \draw[red,shift={(9,\j)},fill](0,0) rectangle (1,1);
        }

        \foreach \i in {0,...,9}{
            \foreach \j in {0,...,9}{
                \draw[shift={(\i,\j)}](0,0) rectangle (1,1);
        }}
        \draw[very thick] (0,0) rectangle (10,10);
        \end{tikzpicture} 

谢谢

答案1

这定义了一个图片,其参数是您所引用的数字,并据此绘制部分填充的正方形。

\documentclass[tikz,border=3mm]{standalone}
\begin{document}
\tikzset{pics/pf/.style={code={\foreach \i in {0,...,9}{
  \foreach \j in {0,...,9}{
   \pgfmathtruncatemacro{\itest}{ifthenelse(\i*10+\j<#1,1,0)}
  \draw[shift={(\i,9-\j)}] \ifnum\itest=1 [fill=red] \fi
  (0,0) rectangle (1,1);
        }}
  \draw[very thick] (0,0) rectangle (10,10);        
}},
pics/pft/.style={code={%
\pgfmathtruncatemacro{\imod}{int(#1/100)}
\path foreach \X in {0,...,\imod}
{(3*\X,0) pic[scale=0.25]{pf=#1-100*\X}};
}}}
\begin{tikzpicture}[baseline={([yshift=-.5ex]current bounding box.center)}]
 \pic{pft=195};        
\end{tikzpicture}
\begin{tikzpicture}[baseline={([yshift=-.5ex]current bounding box.center)}]
 \pic{pft=273};        
\end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

像这样吗?

\documentclass[tikz]{standalone}
\usepackage{tikz}
\newcommand{\redsquare}[1]{%
\foreach \i in {1,...,200}
{
  \pgfmathsetmacro{\RowNo}{mod(\i-1,10)}
  \pgfmathsetmacro{\ColTmp}{floor((\i-1)/10)}
  \pgfmathsetmacro{\ColNo}{ifthenelse(\ColTmp>9,\ColTmp+1,\ColTmp)}
  \typeout{\RowNo,\ColNo}
  \ifnum \i > #1
    \draw[shift={(\ColNo,-\RowNo)},fill=white](0,0) rectangle (1,1);
  \else
    \draw[shift={(\ColNo,-\RowNo)},fill=red](0,0) rectangle (1,1);
  \fi
}
\draw [very thick] (0,1) rectangle +(10,-10);
\draw [very thick] (11,1) rectangle +(10,-10);
}

\begin{document}

\begin{tikzpicture}[scale=0.25]
\redsquare{195}

\begin{scope}[yshift=-13cm]
\redsquare{163}
\end{scope}
\end{tikzpicture}

\end{document}

在此处输入图片描述

相关内容