6

This code:

\documentclass[tikz,border=1mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{backgrounds}

\begin{document}
    \begin{tikzpicture}[scale=4]
        \begin{scope}[on background layer]
            \draw[fill, top color=black, bottom color=white, shading=axis, shading angle=-33.02] 
            (1,1) -- (-1,1) -- (-1,0.8) -- (1,-0.5) -- cycle;
        \end{scope}
    \end{tikzpicture}
\end{document}

produces the following polygon with a color gradient orthogonal to the diagonal line.

enter image description here

I have two problems:

1) The gradient should always be orthogonal to the diagonal line. How can I compute automatically the right angle? Is there another way to define the direction of the gradient / shading?

2) The shading does not really go from white to black. I want the shading to be white at the diagonal line and black in the upper right corner. What is the right way to do that?

2 Answers 2

2

Only for comparism. Run with xelatex:

\documentclass[pstricks,border=1mm]{standalone}
\usepackage{pst-grad}

\begin{document}
\psset{unit=4}
\begin{pspicture}(-1,-0.5)(1,1)
\psclip{\pspolygon[linestyle=none](1,1)(-1,1)(-1,0.8)(1,-0.5)}
  \pspolygon[linestyle=none,fillstyle=gradient,gradbegin=black,
  gradangle=-33,gradend=white,gradmidpoint=0.47](-1.5,1)(1,1)(1,-0.5)
\endpsclip
\pspolygon(1,1)(-1,1)(-1,0.8)(1,-0.5)
\end{pspicture}

\end{document}

enter image description here

2
  • I would like to use as much as possible from the original code in the question. Is that not possible? Your code outputs the desired effect, but is quite different to mine.
    – Gilfoyle
    Jan 10, 2019 at 14:19
  • at least use shading angle=-33
    – user2478
    Jan 10, 2019 at 15:24
2

You definitely do not have to hardcode the shading angle. This answer comes with a style that can be used as

shading angle from={line from (-1,0.8) to (1,-0.5)}

which then inserts the appropriate shading angle

\documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{backgrounds,calc}

\begin{document}
    \begin{tikzpicture}[scale=4,shading angle from/.style args={line from #1 to #2}{
    insert path={let \p1=($#2-#1$),\n1={atan2(\y1,\x1)} in},
    shading angle=\n1}]
        \begin{scope}[on background layer]
            \draw[fill, top color=black, bottom color=white,
            shading angle from={line from (-1,0.8) to (1,-0.5)}] 
            (1,1) -- (-1,1) -- (-1,0.8) -- (1,-0.5) -- cycle;
        \end{scope}
    \end{tikzpicture}
\end{document}

enter image description here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .