TikZ, a drawing library for LaTeX, has some built-in options to fade a path. Sometimes, though, much more control is needed. For this, custom fadings can be defined, but there are some caveats that do not seem to be mentioned in the manual. The following recipe is tested with TikZ version 3.0.1.

The way that custom fadings work is that a picture is defined, which then acts as a mask. Regions of the picture that are filled with the colour transparent will be transparent. Add opacity by “scaling”, e.g. use transparent!50 for 50% transparency. transparent!0 means completely opaque. Regions that are not filled at all are also transparent.

The trick: The real trick to get it to work correctly is that the fading picture must have a size of 2cm · 2cm, otherwise it doesn’t seem to work. This is not mentioned in the manual.

An example would look like this:

\usepackage{tikz}

% must be 2cm*2cm in size
\clip (0,0) rectangle (2,2);
right color=transparent!0]
(0,0) rectangle (0.5,2);
right color=transparent!80]
(0.5,0) rectangle (0.7,2);
right color=transparent!0]
(0.7,0) rectangle (0.9,2);
right color=transparent!0]
(0.9,0) rectangle (1.5,2);
right color=transparent!80]
(1.3,0) rectangle (1.5,2);
right color=transparent!0]
(1.5,0) rectangle (1.7,2);
right color=transparent!0]
(1.7,0) rectangle (2,2);


When applied to a path—\fill [path fading=myfading]—it looks like this:

The dashed box indicates how the fade mask is scaled, i.e., to the bounding box of the path. Fadings can be applied to any path, filled or just lines.

The \shade command also support top color and bottom color. Rotation is a little bit tricky. For simple cases, the shading angle argument can be used. If parts of the fading picture should be rotated, a simple rotate argument is not sufficient, since shadings are applied after rotation. Instead, use transform canvas:

\begin{tikzfadingfrompicture}[name=myfading]
% must be 2cm*2cm in size
\clip (0,0) rectangle (2,2);
\begin{scope}[transform canvas={rotate=20}]
right color=transparent!0]
(0,-1) rectangle (0.51,3);
right color=transparent!80]
(0.5,-1) rectangle (0.71,3);
right color=transparent!0]
(0.7,-1) rectangle (0.91,3);
right color=transparent!0]
(0.9,-1) rectangle (1.51,3);