Apply shading to text

From Wiki
Jump to navigation Jump to search

MetaPost provides shading functions making it easy to fill a path with linear or circular shading. In this simple example, we show how they can be used in conjunction with the outlinetext function and && path combination operator to fill text or equations with a color gradient.

\definecolor[Colour1][h=FF0000]
\definecolor[Colour2][h=880088]
\definecolor[Colour3][h=0000FF]

\define[1]\ShadedText%
    {%
    \startuseMPgraphic{shade_text}
        picture ot ;
        ot := outlinetext("#1") ;       % Get the outline of each symbol
        path p ;                        % Define a new path
        p := (0,0) -- (0,0);
        for i within ot :               % Loop over the symbol outlines
            p := p && pathpart i ;      % Combine p with the new outline
        endfor
        fill p && cycle                 % Fill the path p...
            withshademethod "linear"    % ... with a linear shading...
            withshadedirection (1.,0.)
            withshadestep (             % ... going from Colour1 to Colour2...
                withshadefraction .5
                withshadecolors (\MPcolor{Colour1}, \MPcolor{Colour2})
            )
            withshadestep (
                withshadefraction 1     % ... then from Colour2 to Colour3
                withshadecolors (\MPcolor{Colour2}, \MPcolor{Colour3})
            ) ;
    \stopuseMPgraphic
    \useMPgraphic{shade_text}{}%
    }

\starttext
\startTEXpage
    \ShadedText{test}
    \blank[1em]
    \ShadedText{\dm{\sum_{n=0}^{\infty} 2^{-n} = 2}}
\stopTEXpage
\stoptext

One caveat to be aware of is that some symbols, for instance the fraction bar in some Math fonts, seem to give an outline with no area and will thus not be rendered correctly.