有没有办法绘制一条水平线,其中各部分颜色不同,且每部分长度相同?
下面的代码将产生我想要的结果,但这不是一种优雅的方法。
\begin{figure}[t]
\textcolor{red}{\rule{5cm}{1mm}}
\hspace{-.277cm}\textcolor{green}{\rule{5cm}{1mm}}
\hspace{-.277cm}\textcolor{blue}{\rule{5cm}{1mm}}
\end{figure}
理想情况下,我希望创建具有相对长度的线,并且能够为其着色,而无需将三条单线拼接在一起。
答案1
像这样的东西,会产生一个\coloredrule
命令,该命令采用规则的总长度、宽度和以逗号分隔的颜色列表?
\documentclass{article}
\usepackage{xcolor,etoolbox}
\newlength{\colorsegmentlength}% Used internally
\newlength{\colortotallength}% Used internally
\newcounter{colorcounter}% Used internally
\newcommand{\coloredrulei}[3]{% {segment length}{rule height}{colors}
\renewcommand*{\do}[1]{%
\textcolor{##1}{\rule{#1}{#2}}}
\begingroup\docsvlist{#3}\endgroup}
\newcommand{\coloredrule}[3]{% {total length}{rule height}{colors}
\setlength{\colortotallength}{#1}
\renewcommand*{\do}[1]{%
\stepcounter{colorcounter}}
\setcounter{colorcounter}{0}
\docsvlist{#3}
\setlength{\colorsegmentlength}{%
\dimexpr \numexpr \colortotallength / \value{colorcounter} \relax sp \relax}
\coloredrulei{\colorsegmentlength}{#2}{#3}}
\begin{document}
\coloredrule{20mm}{1cm}{red,orange,yellow,green,blue,violet}
\coloredrule{\textwidth}{2mm}{green,red,yellow,green,red,yellow,green,red,yellow}
\end{document}
(衷心感谢这个答案用于划分长度。)
答案2
这段代码很简单……但确实有效!line width=3pt
你可以增加线条的粗细。
\documentclass[a4paper,12pt]{article}
\usepackage{tikz,xcolor}
\tikzset{every picture/.style={line width=3pt}}
\begin{document}
\begin{tikzpicture}[x=1pt,y=1pt,yscale=-5,xscale=5]
\draw [color=cyan] (0,0) -- (5,0) ;
\draw [color=magenta] (5,0) -- (10,0) ;
\draw [color=brown] (10,0) -- (15,0) ;
\draw [color=green] (15,0) -- (20,0) ;
\draw [color=red] (20,0) -- (25,0) ;
\draw [color=yellow] (25,0) -- (30,0) ;
\draw [color=red] (30,0) -- (35,0) ;
\end{tikzpicture}
\end{document}