我使用循环生成 8 个矩形节点\foreach
,但我希望其中一个(索引处的节点position
)具有灰色背景。
我该怎么做?我想避免重复\node[simd element]
条件跳转的 if 和 else 分支中的命令。
\begin{tikzpicture}
% Definitions
\setlength{\elemwidth}{4ex};
\setlength{\dotswidth}{4ex};
\setlength{\labelsepa}{0.2cm};
\tikzset{simd element/.style={
rectangle,
draw,
inner xsep=0.1ex,
font=\footnotesize\ttfamily,
minimum width=\elemwidth,
minimum height=\heightof{A[0]}+0.666em
}};
%%%% Define variable position := 3
% Source 1
\node[label] (src1lbl) {$I_{ndex}$};
\foreach \val [count=\i] in {04, 03, 06, 0f, 0a, 08, 02, 0c} {
\node[simd element] (src1\i) [right=\labelsepa of src1lbl.east,
xshift=(\i-1)*\elemwidth, outer sep=0] {\val};
%%%% if \i == position
%%%% set background color to gray
}
\end{tikzpicture}
答案1
你可以用不同的方式比较事物,最后将其发送到变量。因此,下面只是许多其他方法中的一种方法,例如将选项存储到键中并相应地选择它们等。这种方法特别简单,因为它假设框中没有先前的填充,因此将它们设置为无。
\usetikzlibrary{positioning} % In the preamble
....
\begin{tikzpicture}
% Definitions - Don't spend register on such simple stuff
\def\elemwidth{4ex};
\def\dotswidth{4ex};
\def\labelsepa{0.2cm};
\tikzset{simd element/.style={
rectangle,
draw,
inner xsep=0.1ex,
font=\footnotesize\ttfamily,
minimum width=\elemwidth,
minimum height=\heightof{A[0]}+0.666em
}};
%%%% Define variable position := 3
\def\mypos{3}
% Source 1
\node[label] (src1lbl) {$I_{ndex}$};
\foreach \val [count=\i] in {04, 03, 06, 0f, 0a, 08, 02, 0c} {
\ifnum\i=\mypos\relax\def\mytestcolor{gray}\else\def\mytestcolor{none}\fi
\node[simd element,fill=\mytestcolor] (src1\i) [right=\labelsepa of src1lbl.east,
xshift=(\i-1)*\elemwidth, outer sep=0] {\val};
%%%% if \i == position
%%%% set background color to gray
}
\end{tikzpicture}