我有一个矩形节点,比如说 2cm 乘以 3cm。
有没有类似 TikZ 的方式填充该矩形的百分比值,比如 p,类似于图中所示(为 34.5%)。
因此黄色区域应为矩形面积的 34.5%。
我这里有一个方法,但这种方法只在 p 小于或等于 50% 时才有效。
在 p 大于 50% 的情况下,填充也不再是三角形。
我该怎么办?
\documentclass[margin=5pt, varwidth]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\begin{tikzpicture}[]
\pgfmathsetmacro\a{2}
\pgfmathsetmacro\b{3}
\pgfmathsetmacro\p{0.345} % percent value
% (x*a * y*b)/2 = p*a*b =>
\pgfmathsetmacro\x{sqrt(2*\p)}
\pgfmathsetmacro\y{sqrt(2*\p)}
% Rectangle
\node[draw, minimum width=\a cm, minimum height=\b cm](X){XYZ};
% Fill
\draw[red, fill=yellow] (X.north west) -- ($(X.north west)!\x!(X.south west)$)
-- ($(X.north west)!\x!(X.north east)$) --cycle;
% Annotation
\node[align=left, anchor=north west] at (X.north east){
a = \a cm \\
b =\b cm \\
p=\p \\
x = \x \\
y = \y
};
\end{tikzpicture}
\end{document}
答案1
我会按照 Sigur 的建议使用剪辑。这样你就不需要 if-then-else 命令了。我提供两种可能性,第一种是直角三角形与矩形边 a 和 b 成比例,第二种是等腰三角形 (x=y)。
\documentclass[border=2mm]{standalone}
\usepackage{tikz}
\def\a{2}
\def\b{3}
\begin{document}
\begin{tikzpicture}[line cap=round, line join=round]
\foreach[count=\i]\p in {0.1,0.345,0.5,0.9}
{%
% proportional triangle
\begin{scope}[shift={(\i*\a+0.5*\i,\b+0.5)}]
\node at (0.5*\a,0.5*\b) {$p=\p$};
\draw[clip] (0,0) rectangle (\a,\b);
\draw[fill=yellow,fill opacity=0.5] (2*\p*\a,\b) -| (0,\b-2*\p*\b) -- cycle;
\end{scope}
% isosceles triangle
\begin{scope}[shift={(\i*\a+0.5*\i,0)}]
\node at (0.5*\a,0.5*\b) {$p=\p$};
\draw[clip] (0,0) rectangle (\a,\b);
\draw[fill=yellow,fill opacity=0.5] (-\b,\b) |- ({-(1-\p)*\b+\p*\a},0) --++ (\b,\b) -- cycle;
\end{scope}
}
\end{tikzpicture}
\end{document}
答案2
\documentclass[margin=5pt, varwidth]{standalone}
\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{backgrounds}
\begin{document}
\begin{tikzpicture}[]
\pgfmathsetmacro\p{0.9} % percent value
\pgfmathsetmacro\a{2}
\pgfmathsetmacro\b{3}
\pgfmathsetmacro\pShow{\p*100}
\pgfmathsetmacro\pTest{\p>0.5 ? 1 : 0}
\pgfmathsetmacro\q{\pTest==1 ? 1-\p : \p}
% (x*a * y*b)/2 = p*a*b =>
\pgfmathsetmacro\x{sqrt(2*\q)}
\pgfmathsetmacro\y{\x}
\ifnum\pTest=1
\colorlet{maincolor}{yellow}
\colorlet{fillcolor}{white}
\else
\colorlet{maincolor}{white}
\colorlet{fillcolor}{yellow}
\fi
% Rectangle
\node[draw, fill=maincolor, minimum width=\a cm, minimum height=\b cm](X){};
\draw[clip] (X.south west) rectangle +(\a,\b);% else not so nice
% Fill
\ifnum\pTest=1
\coordinate[] (C) at (X.south east);
\coordinate[] (A) at ($(X.south east)!\y!(X.north east)$);
\coordinate[] (B) at ($(X.south east)!\x!(X.south west)$);
\else
\coordinate[] (C) at (X.north west);
\coordinate[] (A) at ($(X.north west)!\y!(X.south west)$);
\coordinate[] (B) at ($(X.north west)!\x!(X.north east)$);
\fi
\fill[fillcolor] (A) -- (B) -- (C) --cycle;
\draw[red] (A) -- (B);
\node[anchor=north west, inner sep=1pt] at (X.north west) {\pgfmathprintnumber[precision=1]{\pShow}\%};
\end{tikzpicture}
\end{document}
\pgfmathsetmacro\p{0.9}
也适用于: