代码:
\tikzstyle{matrici}=[
matrix of math nodes,
nodes in empty cells,
column sep=-\pgflinewidth, % to avoid double borders in contiguous cells
nodes={
draw,
align=center,
inner sep=0pt,
text width=1cm,
minimum height=1cm
}
]
\begin{tikzpicture}
\matrix[matrici,
column 1/.style={nodes={fill=blue!10}},
column 2/.style={nodes={fill=blue!10}},
column 3/.style={nodes={fill=blue!10}},
column 4/.style={nodes={fill=blue!10}},
] (X) {&&&&&&&\\};
\end{tikzpicture}
输出:
有没有办法用“cicle for”填充前 4 个单元格?我被迫写这个?
column 1/.style={nodes={fill=blue!10}},
column 2/.style={nodes={fill=blue!10}},
column 3/.style={nodes={fill=blue!10}},
column 4/.style={nodes={fill=blue!10}},
就像
\foreach \x in {1,2,3,4}
fill the node (X-1-\x) with this color
答案1
\fill
您可以向图层添加background
:
\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix,backgrounds}
\tikzset{ % \tikzstyle is considered deprecated
matrici/.style={
matrix of math nodes,
nodes in empty cells,
column sep=-\pgflinewidth, % to avoid double borders in contiguous cells
nodes={
draw,
align=center,
inner sep=0pt,
text width=1cm,
minimum height=1cm
}
}
}
\begin{document}
\begin{tikzpicture}
\matrix[matrici] (X) {&&&&&&&\\};
\begin{scope}[on background layer]
\foreach \x in {1,...,4}
\fill [blue!10] (X-1-\x.south west) rectangle (X-1-\x.north east);
\end{scope}
\end{tikzpicture}
\end{document}
另一个选择是做类似 Loop Space 在他的回答中所做的事情如何在 Tikz 中设置矩阵节点的行和列的背景颜色?:
\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{matrix,backgrounds}
\tikzset{
matrici/.style={
matrix of math nodes,
nodes in empty cells,
column sep=-\pgflinewidth, % to avoid double borders in contiguous cells
nodes={
draw,
align=center,
inner sep=0pt,
text width=1cm,
minimum height=1cm
}
}
}
\begin{document}
\begin{tikzpicture}
\matrix[
matrici,
nodes={
execute at begin node={
\pgfmathparse{\pgfmatrixcurrentcolumn<5 ? "blue!10" : "white"}
\xglobal\colorlet{nodebg}{\pgfmathresult}},
preaction={fill=nodebg}
}
] (X) {&&&&&&&\\};
\end{tikzpicture}
\end{document}
答案2
请原谅我对您的问题的理解不够,但如果您想创建一个彩色框,那么您可以执行以下操作(即,如果我误解了您的问题,请纠正我,因为这对我来说并不完全清楚)。
\documentclass[border={10pt}]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
[%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
colorbox/.style={rectangle,fill=blue!10,draw=black,thick, minimum size=1cm},
box/.style={rectangle,draw=black,thick, minimum size=1cm},
]%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\foreach \x in {0,...,3}
\node[colorbox] at (\x,0){};
\foreach \x in {4,...,7}
\node[box] at (\x,0){};
\end{tikzpicture}
\end{document}