选择特定节点并更改样式(针对这些节点)

选择特定节点并更改样式(针对这些节点)

是否可以选择特定节点并将其涂成绿色?

我正在考虑使用另一个 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当前节点的值。(如果没有.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}

输出

在此处输入图片描述

相关内容