![如何在 TikZ 中将矩形部分填充到一定的相对高度?](https://linux22.com/image/441579/%E5%A6%82%E4%BD%95%E5%9C%A8%20TikZ%20%E4%B8%AD%E5%B0%86%E7%9F%A9%E5%BD%A2%E9%83%A8%E5%88%86%E5%A1%AB%E5%85%85%E5%88%B0%E4%B8%80%E5%AE%9A%E7%9A%84%E7%9B%B8%E5%AF%B9%E9%AB%98%E5%BA%A6%EF%BC%9F.png)
这个答案我们如何在 TikZ 中填充半矩形.south west
,展示了如何使用和.east
属性对矩形进行半填充path picture bounding box
。
我想知道如何概括地填充矩形直至其总高度的一定百分比。
我想仅使用与我想要填充的相对高度相对应的数字来控制颜色填充的高度(例如 22%、58%)。我不想通过手动计算坐标来实现这个相对填充高度。
答案1
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\newcommand\partiallyFilledBox[1]{%
\begin{tikzpicture}
\coordinate (A) at (0,0);
\coordinate (B) at (1,1);
\draw[red,fill=red] (A) rectangle ($(A-|B)!#1!(B)$);
\draw (A) rectangle (B);
\end{tikzpicture}%
}
\begin{document}
\noindent
\partiallyFilledBox{0}
\partiallyFilledBox{0.1}
\partiallyFilledBox{0.2}
\partiallyFilledBox{0.3}
\partiallyFilledBox{0.4}
\partiallyFilledBox{0.5}
\partiallyFilledBox{0.6}
\partiallyFilledBox{0.7}\\
\partiallyFilledBox{0.8}
\partiallyFilledBox{0.9}
\partiallyFilledBox{1.0}
\partiallyFilledBox{1.1}
\partiallyFilledBox{1.2}
\partiallyFilledBox{1.3}
\partiallyFilledBox{1.4}
\partiallyFilledBox{1.5}
\end{document}
答案2
A\pic
在这里可能会有用。
像这样:
\documentclass[tikz,border=2mm]{standalone}
\tikzset
{%
pics/my rectangle/.style n args={3}{% width, height, filling percentage
code={%
\fill (0,0) rectangle (#1,0.01*#2*#3);
\draw (0,0) rectangle (#1,#2);
}},
}
\begin{document}
\begin{tikzpicture}
\pic[draw=red,fill=orange] at (0,0) {my rectangle={2}{3}{25}};
\pic[draw=black,fill=green] at (3,0) {my rectangle={3}{2}{75}};
\end{tikzpicture}
\end{document}
答案3
如果没有任何最简单的例子,很难知道你想如何实现它!?这里有一种方法:
\documentclass[tikz,border=1 cm]{standalone}
\begin{document}
\begin{tikzpicture}
\newcommand{\height}{4 cm}
\fill[red] (0,0) rectangle +(5,0.58*\height);
\fill[green] (0,0) rectangle +(5,0.22*\height);
\draw (0,0) rectangle +(5,\height);
\end{tikzpicture}
\end{document}