我们如何在 TikZ 中填充半矩形

我们如何在 TikZ 中填充半矩形

\filldraw[color=red] (0,0) rectangle (5,4)填充整个矩形的情况下,我们如何在 TikZ 中仅填充矩形的前半部分或第一条对角线

答案1

这就是path pictures 的用途。

\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}
 \begin{tikzpicture}
  \draw[path picture={\fill[red] (path picture bounding box.south west)
  rectangle (path picture bounding box.east);}] (0,0) rectangle  ++ (5,4);
  \draw[path picture={\fill[red] (path picture bounding box.south west)
  -- (path picture bounding box.north east) |-cycle;}] (6,0) rectangle  ++ (5,4);
 \end{tikzpicture}
\end{document}

在此处输入图片描述

当然,这可以转化为样式,并且适用于任意形状,而不仅仅是矩形。

\documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{shapes.symbols}
\begin{document}
 \begin{tikzpicture}[fill lower half/.style={path picture={\fill[#1] (path picture bounding box.south west)
  rectangle (path picture bounding box.east);}},
  fill lower right/.style={path picture={\fill[#1] (path picture bounding box.south west)
  -- (path picture bounding box.north east) |-cycle;}}]
  \draw[fill lower half=red] (0,0) rectangle  ++ (5,4);
  \draw[fill lower right=red] (6,0) rectangle  ++ (5,4);
  \node[cloud,draw,fill lower half=blue,minimum width=4cm,minimum height=3cm] 
  at (2.5,-5){};
  \node[cloud,draw,fill lower right=blue,minimum width=4cm,minimum height=3cm] 
  at (8.5,-5){};
 \end{tikzpicture}
\end{document}

在此处输入图片描述

答案2

\documentclass[tikz,border=3mm]{standalone}
\begin{document}
 \begin{tikzpicture}
  \fill[red]    (0,0) rectangle  ++ (5,2);
  \draw         (0,0) rectangle  ++ (5,4);
 \end{tikzpicture}
 \begin{tikzpicture}
  \fill[blue]   (0,0) -- ++ (5,4) |- cycle;
  \draw         (0,0) rectangle  ++ (5,4);
 \end{tikzpicture}
\end{document}

在此处输入图片描述

相关内容