[Tex/LaTex] Filling rectangle in TikZ with more than one color

colortikz-pgf

To draw a rectangle and fill it in gray in TikZ:

\draw [fill=gray,very thick] (0,0) rectangle (2,1);

Now, I want to fill it in both gray and yellow. The best way would be if I can make diagonal stripes of gray and yellow alternately. Is there a way to do that?

Best Answer

A bit tricky solution without defining custom pattern for rectangle a=2xb.

\documentclass{article}
\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
\def\a{2}%width of rectangle
\def\b{\a/2}%height of rectangle
\def\lw{0.1}
\draw[] (0,0) rectangle (\a,\b);
\foreach \x in{0,0.2,0.4,...,\a}{
\draw [gray,line width=\lw mm](\x,0)--(0,\x/2);
\draw [gray,line width=\lw mm](\a,\x/2)--(\x,\b);}

\foreach \x in{0.1,0.3,...,\a}{
\draw [yellow,line width=\lw mm](\x,0)--(0,\x/2);
\draw [yellow,line width=\lw mm](\a,\x/2)--(\x,\b);}

\end{tikzpicture}

\end{document}

enter image description here