
假设我有一个 \new 命令来绘制 tikz 图片。如何使用节点放置多个这样的图片?具体来说,我有一个命令
\row 按照我想要的方式绘制一排彩色方块。现在我想将其中一些行放在彼此之下。
% x position, y position, colour, number.
\newcommand{\coloredSquare}[4] {
\draw[fill=#3] (#1, #2) +(-.5,-.5) rectangle ++(.5,.5);
\node at (#1, #2) {#4};
}
% Argument one is the row number, argument two is the size of the cache
% line in words.
\newcommand{\row}[2] {
\begin{tikzpicture}
\foreach \b in {1, ..., #2} {
\coloredSquare{#2 * 0 + \b - 1}{0}{green}
{\pgfmathparse{#1 * #2 * 4 + #2 * 0 + \b - 1}\pgfmathresult}
\coloredSquare{#2 * 1 + \b - 1}{0}{yellow}
{\pgfmathparse{#1 * #2 * 4 + #2 * 1 + \b - 1}\pgfmathresult}
\coloredSquare{#2 * 2 + \b - 1}{0}{red}
{\pgfmathparse{#1 * #2 * 4 + #2 * 2 + \b - 1}\pgfmathresult}
\coloredSquare{#2 * 3 + \b - 1}{0}{blue}
{\pgfmathparse{#1 * #2 * 4 + #2 * 3 + \b - 1}\pgfmathresult}
}
\end{tikzpicture}
}
我尝试过类似
% Second argument is the size of the cache line in words,
% the product of the arguments is the total memory size.
\newcommand{\cacheLayout}[2] {
\begin{tikzpicture}
\foreach \a in {1, ..., #1} {
\node at (\a - 1, 0) \row{\a - 1}{#2}
}
\end{tikzpicture}
}
但它没有编译。将所有内容放在一个命令中会产生非常奇怪的结果。
答案1
我想你想要这样的东西:
在本例中,我使用了两个foreach
循环。第一个循环沿着列表跳转row-major index
,并使用该值计算相应行上的第一个数字。
除了行数之外,其他所有值(列数和颜色宽度)都是固定的,但参数化它们并不太困难。
关于每行不同的颜色,我用过杰克的回答到如何使 TikZ 样式取决于比较两个数字样式参数?
\documentclass[tikz,border=1mm]{standalone}
\begin{document}
\begin{tikzpicture}[
byte/.style={draw, fill=#1, minimum size=1cm, outer sep=0pt},
myfill/.is choice,
myfill/1/.style={byte=green!70},
myfill/2/.style={byte=yellow!70},
myfill/3/.style={byte=red!70},
myfill/4/.style={byte=blue!70}]
\foreach \i [count=\row (init from 0)] in {0,20,3,10,5}
\foreach \col in {0,1,...,15}{
\pgfmathtruncatemacro\myfill{ifthenelse(\col<4,1,{ifthenelse(\col<8,2,{ifthenelse(\col<12,3,4)})})}
\node[myfill=\myfill] at (\col, -\row) {\the\numexpr16*\i+\col\relax};}
\end{tikzpicture}
\end{document}