3
\documentclass[tikz]{standalone}

\begin{document}    
    \begin{tikzpicture}
    \draw[->] (0,0) -- (25:8cm) ;
    \end{tikzpicture}  
\end{document}

What would be the correct code to obtain a 8cm black line which is colored in green from 5th centimeter to 7th centimeter?

Nip
  • 215

1 Answers1

9

You can use postaction along with dash pattern for this.

\documentclass[tikz]{standalone}

\begin{document}    
    \begin{tikzpicture}
    \draw[->,postaction={-,draw=green,dash pattern=on 0pt off 5cm on 2cm off 2cm}] (0,0) -- (25:8cm) ;
    \end{tikzpicture}  
\end{document}

enter image description here

EDIT: A somewhat cleaner version (because no line gets overdrawn, which makes a difference if the opacity is nontrivial) which is cast into a style.

\documentclass[tikz,border=3.14mm]{standalone}
\begin{document}    
\begin{tikzpicture}[replace stretch/.style args={from #1 to #2 by #3}{%
/utils/exec=\pgfmathsetmacro{\offlen}{#2-#1},
dash pattern=on #1 off \offlen pt on 10cm,
postaction={#3,dash pattern=on 0pt off #1 on \offlen pt off 10cm}}]
 \draw[->,replace stretch={from 5cm to 7cm by {-,draw=green}}] (0,0) -- ++(25:8cm);
 \draw[->,replace stretch={from 5cm to 7cm by {-,draw=white}}] (0,1) -- ++(25:8cm) ;
 \draw[->,replace stretch={from 5cm to 7cm by {-,draw=none}}] (0,2) -- ++(25:8cm) ;
\end{tikzpicture}  
\end{document}

enter image description here

  • 1
    Clever use of dash pattern. – Weijun Zhou Apr 28 '19 at 03:14
  • Is it possible to use some kind of solid pattern instead of dash? – Nip Apr 28 '19 at 03:32
  • @Nip What precisely do you mean? It is a solid line between 5cm and 7cm. –  Apr 28 '19 at 03:47
  • Well. I tried white instead of green and I see some dots. It is almost unnoticeable tho. I just wanted to understand the code and I found this: https://tex.stackexchange.com/questions/45275/tikz-get-values-for-predefined-dash-patterns – Nip Apr 28 '19 at 03:50
  • 1
    If you think there is dash pattern between 5cm and 7cm then you didn't get the "cleverness" of this method. – Weijun Zhou Apr 28 '19 at 03:52
  • 1
    @Nip I confirm that (with some viewers) you can see relics of the black line if you use white. Do they disappear on you viewer if you do \draw[->,postaction={-,draw=white,line width=0.42pt,dash pattern=on 0pt off 5cm on 2cm off 2cm}] (0,0) -- (25:8cm) ; instead? BTW, if you just want a white gap, you could just do \draw[->,dash pattern=on 5cm off 2cm on 2cm] (0,0) -- (25:8cm) ;. –  Apr 28 '19 at 03:59
  • Marmot, I can still see the dots with the first command line in the comment above. The second command eliminated the dots :) Thank you! – Nip Apr 28 '19 at 04:08
  • 1
    @Nip I added a version with a style that (probably) takes care of all these issues. –  Apr 28 '19 at 04:18