2
\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?

  • 1
    Add more points to your path. – Weijun Zhou Apr 28 at 3:02
7

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 at 3:14
  • Is it possible to use some kind of solid pattern instead of dash? – Nip Apr 28 at 3:32
  • 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 at 3: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) ;. – user121799 Apr 28 at 3:59
  • 1
    @Nip I added a version with a style that (probably) takes care of all these issues. – user121799 Apr 28 at 4:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.