![使用循环填充具有多个顶点的多边形](https://linux22.com/image/421407/%E4%BD%BF%E7%94%A8%E5%BE%AA%E7%8E%AF%E5%A1%AB%E5%85%85%E5%85%B7%E6%9C%89%E5%A4%9A%E4%B8%AA%E9%A1%B6%E7%82%B9%E7%9A%84%E5%A4%9A%E8%BE%B9%E5%BD%A2.png)
我有一个包含许多顶点的多边形。我首先使用
\foreach \i in {1,...,\n}
{
\coordinate (\i) at (\x,\y);
\coordinate (p\i) at (\z,\t);
}
有一系列关于\x
、\y
、\z
和\t
的计算不相关,因此我省略了这些行。
我需要填充由坐标定义的多边形。我必须写
(1)--(p1)--(p2)--(2)--(3)--(p3)--(p4)--
等等,或者有没有办法可以循环执行此操作?
我可以按如下方式编写循环
\foreach [evaluate ={\j=int(mod(\i,2)); \k=\i+1;}] \i in {1,...,\n}
{
\ifthenelse{\j = 1}
{
\draw (\i)--(p\i)--(p\k)--(\k);
}
{
\draw (\i)--(\k);
}
}
仅绘制多边形。我能以某种方式命名多边形然后填充它吗?
以下是 MWE:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}
\coordinate (1) at (0,0);
\coordinate (2) at (0,10);
\coordinate (3) at (10,10);
\coordinate (4) at (10,0);
\fill[gray] (1)--(2)--(3)--(4); % I want to do this line in a \foreach loop
\end{tikzpicture}
\end{figure}
\end{document}
答案1
尝试
\fill[gray] (1) foreach \n in {2,...,5} {--(\n)} --cycle;
如果我要尝试翻译你的例子,我可能会按 2 步并将你的条件的两种情况结合起来,如下所示:
\fill[gray] (1) foreach [evaluate ={\j=\i+1; \k=\i+2;}] \i in {1,3,...,\n}
{
--(p\i)--(p\j)--(\j) -- (\k)
} -- cycle;
我不确定这是否确实有效但类似的事情会起作用。
完整代码:
\documentclass{article}
\usepackage{tikz}
\begin{document}
\begin{figure}
\centering
\begin{tikzpicture}
\coordinate (1) at (0,0);
\coordinate (2) at (0,10);
\coordinate (3) at (10,10);
\coordinate (4) at (10,0);
\coordinate (5) at (5, -5);
\fill[gray] (1) foreach \n in {2,...,5} {--(\n)} --cycle;
\end{tikzpicture}
\end{figure}
\end{document}
答案2
你可以填充所有单个三角形:
€dit:我添加了\pgfmathsetmacro\StartCornerForFilling{2}
\documentclass[margin=5pt, tikz]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[scale=0.5]
\pgfmathsetmacro\Corners{5} % Number of corners
\pgfmathsetmacro\StartCornerForFilling{2}
% Coordinates
\coordinate[label=left:1] (1) at (0,0);
\coordinate[label=2] (2) at (0,10);
\coordinate[label=3] (3) at (10,10);
\coordinate[label=right:4] (4) at (10,0);
\coordinate[label=below:5] (5) at (5, -5);
\coordinate[label=below:6] (6) at (4, -6); % test
\coordinate[label=below:7] (7) at (1, -4); % test
\coordinate[label=below:8] (8) at (0.5, -3); % test
\pgfmathtruncatemacro\NoTriangles{\Corners-2}
\foreach[count=\No from 0] \n in {1,...,\NoTriangles} {
\pgfmathsetmacro\P{\StartCornerForFilling}
\pgfmathtruncatemacro\Q{1+mod(\P+\n-1,\Corners))}
\pgfmathtruncatemacro\R{1+mod(\P+\n,\Corners))}
\pgfmathsetmacro\colorpercent{100/\n}
\fill[yellow!\colorpercent!red, opacity=0.4] (\P) -- (\Q) -- (\R) --cycle;
\draw[] (\P) -- (\Q) -- (\R) --cycle;
% Annotations 1/2
\node[right of=3, yshift=-0.7*\No cm, anchor=north west]{
$\Delta_{\n}:$ {\P} -- {\Q} -- {\R}};
}
% Annotations 2/2
\node[above of=2, font=\bfseries, anchor=west]{
convex \Corners-polygon $\Rightarrow$ {\NoTriangles} triangles
};
\end{tikzpicture}
\end{document}