Take the 2-minute tour ×
TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. It's 100% free, no registration required.

I want to declare a new shape in TikZ using \pgfdeclareshape. This shape will be formed from several parts, but often, when invoking the shape, I won't want all of the parts displayed. It would be ideal if I could pass some parameters or options when invoking the shape, and draw the shape differently in \backgroundpath depending on the parameters that are passed. Is this possible?

The anchors won't depend on the parameter, just which parts of the backgroundpath are drawn.

share|improve this question
add comment

1 Answer

up vote 7 down vote accepted

This is what \pgfkeys is for! You can set various options in the \pgfdeclareshape pieces that look at the settings of various keys and act accordingly.

As an example, in my TQFT Package, I have keys that set the number of incoming and outgoing boundary components and the shape is drawn accordingly. Other keys control the style of the various pieces and determine which are drawn and which are not.

To do exactly what you want, you could define a new conditional key.

\newif\ifdrawnodepieces
\pgfkeys{/tikz/my shape/drawnodepieces/.is if=drawnodepieces}

Then in the \pgfdeclareshape code you have:

\ifdrawnodepieces
Code if set
\else
Code if not set
\fi

More complicated things are possible, such as changing the style of the path according to the settings. You could save a style (make sure you initialise it in the preamble):

\node[my shape,my shape/path/.style={fill,draw,red,line width=5cm}] {};

and then invoke it in the shape:

\pgfsys@beginscope
  \tikzset{my shape/path}
  \tikz@mode
  \tikz@options
     draw path (using \pgfpath commands)
  \edef\tikz@temp{\noexpand\pgfusepath{%
      \iftikz@mode@fill fill,\fi%
      \iftikz@mode@draw draw\fi%
  }}%
  \tikz@temp
  \pgfsys@endscope

If you use TikZ-type commands in your shape (not recommended) then you can just invoke the style directly:

\path[my shape/path] (0,0) -- (2,0);

It is even possible to change the anchors of the node according to the parameters - I do this in the aforementioned TQFT package but I stole the idea from pgflibraryshapes.geometric.code.tex where the number of sides of a regular polygon depends on a parameter, and since each side gains an anchor then that must also vary.

share|improve this answer
    
Thanks Andrew -- as always, just what I needed. –  Jamie Vicary Jun 14 '11 at 15:20
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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