5

I want to position a node relative to a \pic. I'm able to position a \pic relative to a node, but I want it the other way.

\documentclass{standalone}
\usepackage{tikz}

\tikzset{
    pics/mp3/.style args={scale #1}{
        code={
            \begin{scope}[scale=#1,every node/.style={scale=0.8*#1}]
                \draw[rounded corners=10*#1] (-3,-1) rectangle (3,1);
                \draw[rounded corners=5*#1] (2.8,0.5) rectangle (1.8,-0.5);
                \draw[rounded corners=5*#1] (-1.5,0.6) rectangle (1.5,-0.6);
            \end{scope}
        }
    }
}

\begin{document} \begin{tikzpicture}
    %% Position a pic relative to a node:
    \node (foo) at (0,2) {blubber};
    \pic[above of=foo] {mp3={scale .5}};

    %% Position a node relative to a pic:
    \pic (bar) at (0,-2) {mp3={scale .5}}; %% This doesn't create a named shape.
    %\node[below of=bar] {bimbaz}; %% Package pgf Error: No shape named bar is known.

\end{tikzpicture} \end{document}

So, is there any way to name this \pic?

svenwltr
  • 155
  • 7

1 Answers1

8

You can name internal objects and refer to them by using the pic name later.

\documentclass[tikz]{standalone}
\usetikzlibrary{positioning}
\tikzset{
  pics/mp3/.style={
    code={
        \node[rounded corners=10*#1,draw,anchor=center,
             minimum height=2cm,minimum width=6cm,
             transform shape] (-cover) at (0,0) {};
        \draw[rounded corners=5*#1] (2.8cm,0.5cm) rectangle (1.8cm,-0.5cm);
        \draw[rounded corners=5*#1] (-1.5cm,0.6cm) rectangle (1.5cm,-0.6cm);
    }
  }
}

\begin{document} 
\begin{tikzpicture}
    \node (foo) at (0,2) {blubber};
    \pic[below left= of foo,scale=0.5] {mp3=.5};

    \pic[scale=0.5] (b) at (0,-2) {mp3=.5};
    \node[below= 5mm of b-cover] {bimbaz};
\end{tikzpicture} 
\end{document}

enter image description here

A few remarks;

  • You don't need to use a /.style args handler if you have a single argument. The regular /.style handler has one argument by default hence you can directly use mp3=0.5 using mp3/.style={..... #1 code ....}
  • It might be a good practice if you drop the below of or <direction> of= syntax and switch to the more stable positioning library syntax that is shifting the of to the other side of the equal sign. More in Difference between "right of=" and "right=of" in PGF/TikZ
  • Scaling of the objects should best be left to TikZ itself. So I've put an example to show that you can do it externally too.
percusse
  • 157,807