拉伸 tikz 节点

拉伸 tikz 节点

我想实现某种机制,可以将一组 tikz 节点整齐地并排对齐,并让它们自动拉伸以覆盖页面宽度。请考虑以下示例:

\documentclass{article}
\usepackage{tikz}

\expandafter\def\csname color0\endcsname{red}
\expandafter\def\csname color1\endcsname{green}
\expandafter\def\csname color2\endcsname{blue}

\newcount\nodenum
\newcommand\newnode[1]{
  \pgfmathtruncatemacro\lastnode{\the\nodenum}
  \advance\nodenum by1
  \pgfmathtruncatemacro\thisnode{\the\nodenum}
  \pgfmathtruncatemacro\thiscolor{mod(\the\nodenum,3)}
  \node[anchor=west,fill=\csname color\thiscolor\endcsname] (\thisnode) at (\lastnode.east) {#1};
}
\newenvironment{stretchnodes}{
  \nodenum=-1
  \begin{tikzpicture}[text height=.7em,text depth=.2em]
    \coordinate(-1) at (0,0);
}{
  \end{tikzpicture}
}

\begin{document}
\begin{stretchnodes}
  \newnode{hello}
  \newnode{world}
  \newnode{my}
  \newnode{name}
  \newnode{is}
  \newnode{\dots}
\end{stretchnodes}
\end{document}

输出如下所示: 电流输出

这几乎就是我想要的,除了:

  • 我想删除节点之间的小白色条纹,使它们紧密对齐。
  • 我希望节点自动根据其当前大小按比例拉伸,以便覆盖整个文本宽度。

关于如何实现这一点有什么建议吗?

答案1

下面的定义定义了一个宏

\colorspread[width, default \textwidth]{list of items to be spread}{list of colors}

例如,命令

\colorspread{Hello\ it's\ me\ again}{{red!30}{green!30}{blue!30}}
\colorspread{{Hello}{it's}{me}{again}}{{red!30}{green!30}{blue!30}}
\colorspread[200pt]{Hello\ it's\ me\ again}{{red!30}{green!30}{blue!30}}
\colorspread[100pt]{{Hello}{it's}{me}{again}}{{red!30}{green!30}{blue!30}}

输出结果

在此处输入图片描述

\documentclass{article}
\usepackage{xcolor}
\newlength\paddingwidth
\newcounter{numberofitems}
\newcommand\itemsend{\itemsend}
\newcommand\countitems[1]%
  {\ifx\itemsend#1\let\tmp\relax\else
   \stepcounter{numberofitems}%
   \let\tmp\countitems
   \fi
   \tmp
  }
\newcommand\typesetitems[1]%
  {\ifx\itemsend#1\let\tmp\relax\else
   \typesetitem{#1}%
   \let\tmp\typesetitems
   \fi
   \tmp
  }
\newcommand\colorspreadcolors{}
\newcommand\colorspread[3][\textwidth]%
  {\bgroup
   \settowidth\paddingwidth{#2}%
   \addtolength\paddingwidth{-#1}%
   \setcounter{numberofitems}{0}%
   \countitems#2\itemsend
   \divide\paddingwidth by \value{numberofitems}\relax
   \paddingwidth=-0.5\paddingwidth
   \def\colorspreadcolors{#3#3#3}% Make sure that there are at least three colors
   \typesetitems#2\itemsend
   \egroup
  }
\newcommand\nextcolorspreadcolor{}
\def\nextcolorspreadcolor#1#2\itemsend
  {\def\colorspreadcolors{#2{#1}}%
   \def\tmp{#1}%
  }
\newcommand\typesetitem[1]%
  {\expandafter\nextcolorspreadcolor\colorspreadcolors\itemsend
   \setlength{\fboxsep}{0pt}%
   \colorbox{\tmp}{\strut\hspace*{\paddingwidth}#1\hspace*{\paddingwidth}}%
  }
\begin{document}
\noindent
\colorspread{Hello\ it's\ me\ again}{{red!30}{green!30}{blue!30}}

\noindent
\colorspread{{Hello}{it's}{me}{again}}{{red!30}{green!30}{blue!30}}

\noindent
\colorspread[200pt]{Hello\ it's\ me\ again}{{red!30}{green!30}{blue!30}}

\noindent
\colorspread[100pt]{{Hello}{it's}{me}{again}}{{red!30}{green!30}{blue!30}}
\end{document}

相关内容