[Tex/LaTex] Cylinder shading with PGF/TikZ

nodesshadingtikz-pgf

I'm trying to create a cylinder with 3D shading effects. The cylinders in the picture are standing vertically, and have a body and an end. I'd like the body to be shaded so that it varies uniformly from dark on the left side of the cylinder body to light in the middle (facing the viewer) to dark on the right again (light shading effect). The color should remain the same in a vertical direction. If the same is possible for the cylinder end that would be nice, but it is not so important.

I did some experimentation. Cylinder A below has some shading effect, but I have no idea how I got it. I don't even know whether it makes sense to use shade as an argument to a node, except that it is clearly doing something.

Cylinder B is similar to what I want, except for the shading effect.

This was tested with PGF 2.0 and Tex Live 2009 on Debian squeeze.

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{shapes.geometric,decorations.fractals,shadows}
\usepackage[active,tightpage]{preview}
\PreviewEnvironment{tikzpicture}
\begin{document}
\pagestyle{empty}
\begin{tikzpicture}    
\tikzset{draw, name=s, shape=cylinder, line width=0.1cm, shape
    border rotate=90, aspect=.2, inner xsep=3cm, inner ysep=2cm,
    cylinder uses custom fill, cylinder end fill=blue!25, cylinder
    body fill=blue!40};
  \node [aspect=0.25, shade={left color=red!20,right color=blue!50}] at (1,0) {A};
  \node[aspect=0.10] at (10,0) {B};
\end{tikzpicture}
\end{document}

Best Answer

For creating a standalone cylinder, without using the predefined TikZ shapes, you can do something like this:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{calc}
\begin{document}
\pagestyle{empty}
\begin{tikzpicture}    
   \coordinate (ll) at (-3,-2);
   \coordinate (lr) at (3,-2);
   \coordinate (ul) at (-3,2);
   \coordinate (ur) at (3,2);
   \shade [shading angle=90] (ll) arc (-180:-60:3cm and .75cm) -- +(0,4) arc (-60:-180:3cm and .75cm) -- cycle;
   \shade [shading angle=270] (lr) arc (0:-60:3cm and .75cm) -- +(0,4) arc (-60:0:3cm and .75cm) -- cycle;
   \draw [thick] (ll) arc (-180:0:3cm and .75cm) -- (ur) arc (0:-180:3cm and .75cm) -- cycle;
   \draw [thick, shade, shading angle=30] (ul) arc (-180:180:3cm and .75cm);
   \node at (0,-.75){\Huge A};
\end{tikzpicture}
\end{document}