
我正在拼命地努力讓這項工作成功
\documentclass{minimal}
\usepackage{tikz}
\newcommand\polygon[3][]{
\pgfmathsetmacro{\angle}{360/#2}
\pgfmathsetmacro{\startangle}{0}
\begin{scope}[#1]
\draw \foreach\i in {1,...,#2}{
\pgfmathsetmacro{\x}{cos(\startangle + \angle*\i)*#3}
\pgfmathsetmacro{\y}{sin(\startangle + \angle*\i)*#3}
\ifnum\i=1 \else--\fi ({\x},{\y})
};
\end{scope}
}
\begin{document}
\begin{tikzpicture}
\polygon{5}{1}
\end{tikzpicture}
\end{document}
我在網路上四處搜尋,試圖從其他人的問題中獲取可以幫助我完成這項工作的提示,但我仍然收到此錯誤
Package tikz Error: Giving up on this path. Did you forget a semicolon?.
我錯過了什麼?我之前沒有使用 TikZ 的經驗。
更新:\pgfmathsetmacro
經過幾次嘗試後,我才意識到我的問題在某種程度上與循環內的 兩個有關。關於如何讓它發揮作用有什麼建議嗎?
答案1
你想要這樣的東西嗎?
\documentclass[tikz,border=5pt]{standalone}
\newcommand\polygon[3][]{
\pgfmathsetmacro{\angle}{360/#2}
\pgfmathsetmacro{\startangle}{0}
\begin{scope}[#1]
\draw \foreach\i in {1,...,#2}{
\ifnum\i=1 \else--\fi ({cos(\startangle + \angle*\i)*#3},{sin(\startangle + \angle*\i)*#3})
};
\end{scope}
}
\begin{document}
\begin{tikzpicture}
\polygon{5}{1}
\end{tikzpicture}
\end{document}
我認為您不能\pgfsetmacro
在路徑中間使用類似的東西,但您可以將計算放入座標規範中。
這會產生一個開放的五邊形:
minimal
順便說一句,不要使用範例。
編輯
請注意,您也可以使用pic
.我不確切知道您想要在範圍規範中放入什麼內容,但您可以使用pic actions
以下方法傳遞一些內容:
\documentclass[tikz,border=5pt]{standalone}
\tikzset{
pics/open polygon/.style n args=2{
code={
\pgfmathsetmacro{\angle}{360/#1}
\pgfmathsetmacro{\startangle}{0}
\draw [pic actions] \foreach\i in {1,...,#1}{
\ifnum\i=1 \else--\fi ({cos(\startangle + \angle*\i)*#2},{sin(\startangle + \angle*\i)*#2})
};
}
},
}
\begin{document}
\begin{tikzpicture}
\pic [draw=cyan!50!blue, outer color=cyan!50!blue, inner color=cyan!15] {open polygon={5}{1}};
\end{tikzpicture}
\end{document}
答案2
問題出在\draw
路徑內部的計算宏上。因此,我建議將計算與繪圖分開,首先執行計算並將結果儲存在標記為, , ...,\coordinate
的 s中,然後藉助這些座標繪製路徑。以下是您可以執行此操作的方法:a-1
a-2
a-n
\documentclass{standalone}
\usepackage{tikz}
\newcommand\polygon[3][]{
\pgfmathsetmacro{\angle}{360/#2}
\pgfmathsetmacro{\startangle}{0}
\begin{scope}[#1]
\foreach\i in {1,...,#2}{
\pgfmathsetmacro{\x}{cos(\startangle + \angle*\i)*#3}
\pgfmathsetmacro{\y}{sin(\startangle + \angle*\i)*#3}
\coordinate (a-\i) at ({\x},{\y});
}
\draw\foreach \i in{1,...,#2}{\ifnum\i=1 \else --\fi (a-\i)};
\end{scope}
}
\begin{document}
\begin{tikzpicture}
\polygon{5}{1}
\end{tikzpicture}
\end{document}