是否可以選擇特定節點並將其著色為綠色?
我正在考慮使用另一個 for 循環,但似乎我不能定義超過 1 種樣式。
\documentclass{article}
\usepackage[dvipsnames]{xcolor}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}[darkstyle/.style={circle,draw,fill=MidnightBlue!25,minimum size=2.0em}][lightstyle/.style={circle,draw,fill=Green!25,minimum size=2.0em}
\foreach \x in {0,...,4}
\foreach \y in {0,...,4}
{\pgfmathtruncatemacro{\label}{5 + 5*\x - \y}
\node [darkstyle] (\x\y) at (1.5*\x,-1.5*\y) {\label};}
\foreach \x in {0,...,4}
\foreach \y [count=\yi] in {0,...,3}
\draw (\x\y)--(\x\yi) (\y\x)--(\yi\x) ;
\foreach \x in {0,...,4}
\for each \y in {0, 4}
\node [lightstyle]
\end{tikzpicture}
\end{document}
答案1
你可以.try
具有以下組合名稱的樣式X和y當前節點的值。 (如果沒有.try
處理程序,您需要定義每種可能的樣式組合。)
遺憾的是,\tikzset
不能在循環內使用,\foreach
因為它僅在本地執行其主體。我考慮過定義全域 PGF 金鑰,但我認為該etoolbox
解決方案更容易適應。
循環\foreach
「收集」\tikzset
我們稍後用 執行的所有內容\myTikZsets
。
代碼1
\RequirePackage[dvipsnames]{xcolor}
\documentclass[tikz]{standalone}
\usepackage{etoolbox}
\begin{document}
\begin{tikzpicture}[
every node/.style={circle,draw,minimum size=2.0em},
darkstyle/.style={fill=MidnightBlue!25},
lightstyle/.style={fill=Green!25},
redstyle/.style={fill=red!25},
style for 1-3/.style={redstyle},
style for 3-3/.style={redstyle},
]
\foreach \x in {0,...,4} {
\foreach \y in {0,4} {
\xappto\myTikZsets{\noexpand\tikzset{style for \x-\y/.style=lightstyle}}
}
}
\myTikZsets % use the stored \tikzset calls
\renewcommand*{\myTikZsets}{}% and empty it again (for later use)
\foreach \x in {0,...,4}
\foreach \y in {0,...,4}
{\pgfmathtruncatemacro{\label}{5 + 5*\x - \y}
\node [darkstyle, style for \x-\y/.try] (n-\x-\y) at (1.5*\x,-1.5*\y) {\label};}
\foreach \x in {0,...,4}
\foreach \y [count=\yi] in {0,...,3}
\draw (n-\x-\y)--(n-\x-\yi) (n-\y-\x)--(n-\yi-\x) ;
\end{tikzpicture}
\end{document}
代碼2
根據您給出的範例,這也可以使用純 TeX 來完成\ifnum
。
\RequirePackage[dvipsnames]{xcolor}
\documentclass[tikz,convert=false]{standalone}
\begin{document}
\begin{tikzpicture}[
every node/.style={circle,draw,minimum size=2.0em},
darkstyle/.style={fill=MidnightBlue!25},
lightstyle/.style={fill=Green!25},
]
\foreach \x in {0,...,4}
\foreach \y in {0,...,4}
{\pgfmathtruncatemacro{\label}{5 + 5*\x - \y}
\ifnum\y=0
\tikzset{darkstyle/.style={lightstyle}}
\fi
\ifnum\y=4
\tikzset{darkstyle/.style={lightstyle}}
\fi
\node [darkstyle] (n-\x-\y) at (1.5*\x,-1.5*\y) {\label};}
\foreach \x in {0,...,4}
\foreach \y [count=\yi] in {0,...,3}
\draw (n-\x-\y)--(n-\x-\yi) (n-\y-\x)--(n-\yi-\x) ;
\end{tikzpicture}
\end{document}